I am making a distributed system in c++ gnu, ubuntu . A client sends a message to server and then the client will disconnect. I use recv() to get message from client socket. But the problem is, the data is sent in fragment, how can the server know if the message from client has been completely sent to server? Because once the server determines that the current recieved fragment is the last one in the message, the server will do some processing. But how can sever know when the current fragment is the last one.
The message length from client is not constant . The server can't just stay in a recv loop until the client disconnect. It ought to break the msg receiving loop once it knows it has recieved the whole msg from client
When the client has is finished sending recv() will return zero. You know then that it's finished. You should write your recv() and send() calls in a loop. In TCP/IP either one is not guarenteed to complete the read in one pass!
Is there any way I can use select() to solve this problem? any one can provide some example of use of select() in socket prgramming? I find myself diffcult to understand those examples on the web. thanks very much.
Select will give you greater control especially if you are handling more than one socket in a thread. You should set up a simple test between a test client on Windows and another client on Linux and test out what I said first.
because I tried your suggestion in your first reply. It seems that, you mean that I should use non-blocking recv in a loop. So firstly I use blocking recv to wait for the first fragment of the msg from client, then enters a loop calling non-blocking recv, which will break if non-blocking recv returns <=0. But it seems that, once the first blocking recv gets a fragment of the msg, the program will never step into the next non-blocking recv loop, because non-blocking recv loop never returns >0. Is it because that the loop is running too fast so that when non-blocking recv runs, the message fragment is not transmitted to server yet?
No, I never use non-blocking receives. If any recv returns < 0, it is an error. If recv returns 0, that means the other side is finished sending. If recv returns > 0, you have data. I would use a blocking recv with a timeout around the loop. That way, you won't hang forever.