stream socket problem
I am currently using GCC compiler and SunSolaris 8 as my platform. I am trying to program a stream socket (TCP) that send two messages to the server. The code is as follow:
send(socket, msg, strlen(msg));
send(socket, msg1, strlen(msg1));
The server is using 2 recv() to receive the corresponding messages. However, the first recv() sometimes receive both the msg & msg1 together and the second recv() receives nothing thus hanging the whole program. Even worse is that sometimes the first recv() recieves the whole msg but part of the msg1, then the second recv() receives the rest of the msg1.
I have tried to put sleep(1) between the two send() and it solved the problem, however due to performance reason I have got to remove the 1 second delay.
This is kind of weird, could somebody help me in that?
Thanks and regards,
send and recv are not synchronised in any way - there is not a 1:1 relationship between them, so your message passing protocol has to take this into account.
In particular, each message should encode the length of the message in some way, so that the recv can work out how much data to expect.
So you would need
int len = strlen(msg1);
send(socket, &len, sizeof(len);
send(socket, msg, len );
recv returns an integer result specifying how many bytes it managed to get on this particular call. You need to call this in a while loop, until you've received the expected number of bytes (from the lengths encoded in the message).
I use the same method of sending the size of the data first.
A SWITCH is used to determine if data or sizeof data is being recieved or all has been received.( I also have to take into account that all of the data may not arrive at once.)
The first part is waiting for the data size (Len). A buffer is allocated mem for the data.
The second waits for this amount of data (Len), selectively copying it to a buffer allocated in the first case, remembering how much is in the buffer and how much to go.
The third part of the switch can only be reached if all the data for the buffer has been received and copied to the buffer. This sends of the data to the where it is needed and resets for the next incomming data (continuing if there is still data to be used from the recv).
All of this is in a while loop until all the data in the incomming buffer (return from recv) is used/copied.