I have been programming in C++ for a while but I am a beginner to network programming and I am unclear on a couple of things so this is a three part question.
-
In example applications, I have seen a call to send() on one socket, a check of its return value, and then immediately after, a call to recv() on the same socket. I find this confusing however as recv() is not called until after send() so is there not a risk that a reply message will arrive before recv is called? If so is this actually a problem or will the message just hang in limbo until recv is called and it is received?
-
I wish to write a class which communicates with a server, and can make several different kinds of request to the server, with one function for each which sends a request then waits for a reply. My client will have an instance of this class as a member. Given that send() and recv() are blocking calls, even if I create a seperate thread for network communications how can I stop all network communications from being halted while waiting for a reply to one request? If one message fails then until send/recv times out I wont be able to make any more requests, so do I need more than one socket per client? More than one thread?
-
I have been reading about thread safety, and given that send and recv are blocking calls I assume that my application will be threadsafe if I only have one thread per client for network communications, however if I do need more than one thread or more than one socket for each client (which I don’t know yet), how will I go about making it thread safe?
Sorry this was so long.
Thanks.
The mechanism is not so simple. There may be buffers involved on the client side, on the server side or both. For example, a send on the client side may be considered completed when the message was copied to the buffer, not when it is actually sent down the wire. Similarly, messages will be copied to a buffer on the server-side, such that a send from the client matches a receive on the server. Don’t worry about this aspect.
I would not advise you to do several sends from different threads on the same socket. It would probably be better to put the requests in a queue and have a single thread send them to the server. You can then wait for the reply on a separate thread if you wish.
See number 2.