I've implemented a C socket server that is a slight adaptation of the example server here:
http://www.tutorialspoint.com/unix_sockets/socket_server_example.htm
It is using the first example without forking, because there will only ever be one single connection to it. The changes I have made are to move the bzero and read command to a separate function, then in the main function, I wrap the call to that separate function in a do/while loop. I also changed the read command to recv. So, it looks something like this, pseudocode-wise:
int main( int argc, char *argv[] )
{
... (code from the sample code I linked to above) ...
if (newsockfd < 0) {
perror("ERROR on accept");
exit(1);
}
puts("Connected.");
do{
res = doStuff(newsockfd);
} while(res > 0);
puts("Disconnected.");
close(newsockfd);
...
}
int doStuff(int socket){
...
int n;
uint8_t *buf = (uint8_t *) malloc(4);
uint8_t *packet;
bzero(buf, 4);
n = recv(socket, buf, 4, 0);
if(n<=0) { return(n); }
(... do stuff, including creating a packet of a certain size ...)
if (send(socket, packet, packetLength, MSG_DONTWAIT) == -1) {
puts("Error with send");
return(-1);
}
return(1);
}
Good news is, this works most of the time. I'm able to connect from my c# client, send multiple messages, and get messages back to the client. I am sending numerous request msesages from the c# client to the C socket server, one right after the other.
Bad news is, sometimes it doesn't work, and it looks like the C server sends some packets to the C client, and the C client adds them together into a single packet.
For example, I sent three messages from the client to the C server in succession, requesting responses of different byte sizes. The C server received the requests and sent them back, and according to the printout on the screen, in the right order. Example, it said something like this: "Received request for 12 bytes. Sent 12 bytes back. Received request for 5 bytes. Sent 5 bytes back. Received request for 18 bytes. Sent 18 bytes back."
So the C server should have received 3 separate packets, one with 12 bytes, one with 5 bytes, one with 18 bytes. Instead, it gets 1 packet with 35 bytes, which is 12+5+18, then it outputs an error because it was expecting a 12-byte packet next. On the C# side, using receive().
Can anyone give me a clue on where I can look to debug this? Thank you.
Edited to add: The packets being sent back and forth are of varying size, but always a hex byte array (like 0x00, 0x42, 0x01, etc)