read returns junk
I ve written a simple client server,where a server waits on select for handling multiple client.
For load purposes I have connected only a single client and sending 200o msgs continuously.
I have noticed that after some time server reads junk data from the socket.
Its is only when i apply usleep after write in client,server is able to read correct data.
I ve tried using option like TCP_NODELAY and fysnc on socket but it does not help.
I am attaching client and server code files.
I am stuck in this problem from last 2 days.
Several things to mention for the server (I didn't look at the client)
1. struct client_data clients;
This is shared between two threads, but is NOT guarded by a mutex. In particular, you make it valid before assigning other fields.
You could easily avoid all this threading headache by adding listen_fd to the descriptor set monitored by select.
2. ret = select(0xffff, &fds, NULL,NULL,&timeout);
Read the manual page for select, and pass a much better parameter than 0xffff
This will hurt you, checking 1000's of descriptors you have no interest in.
Or more to the point, why not zero?
Or even "why bother", since you're about to overwrite it anyway.
4. ret = read(clients[i].fd,&sock_data,sizeof(sock_data));
You check for <= 0, but what you DON'T check for is ret == sizeof(sock_data)
For a stream connection, message fragmentation can occur on both the sender and receiver side.
You try to send
It is wrong to assume that you will get exactly TWO corresponding read calls at the other end. You might only get "Hel" on the first call. It isn't a failure, but it isn't entirely success either. You need to take this into account and call read again for the remaining bytes you're expecting.
Likewise, on the send side, sending "Hello" might only manage to send "He" on the first call. You would need to detect this and call send again with the remains of the message ("llo" in this case), possibly repeatedly until the whole message is sent.