The basics of Client/Server socket programming

While Client/Server communication model is ubiquitous nowadays, most of them involve socket programming knowledge. In this post, I will introduce some rudimentary aspects of it:

(1) Short/Long-livedTCPconnection.Short-livedTCPconnection refers to following pattern: Client creates a connection to server; send message, then close the connection. If Client wants to transmit information again, repeat the above steps. Because establishing and destroyingTCPsessions have overhead, if Client needs to have transactions with Server frequently, long-lived connection may be a better choice: connect Server; deliver message, deliver message, ..., disconnect Server. A caveat about long-lived connection is Client may need to send heartbeat message to Server to keep theTCPsession active.

(2) Synchronous/Asynchronous communication.After Client sends the request, it can block here to wait for Server's response, this is called synchronous mode. Certainly the Client should set a timer in case the response never come. The Client can also choose not to block, and continue to do other things. On the contrary, this is called asynchronous mode. If the Client can send multiple requests before receiving responses, it needs to add ID for every message, so it can distinguish the corresponding response for every request.

(3) Error handling.A big pain point of socket programming is you need to consider so many exceptional cases. For example, the Server suddenly crashes; the network cable is plugged out, or the response message is half-received, etc. So your code should process as many abnormalities as possible. It is no exaggeration to say that error-handling code quality is the cornerstone of program's robustness.

(4) Portability.Different*NIXflavors may have small divergences on socket programming, so the program works well onLinuxmay not guarantee it also run as you expect onFreeBSD. BTW, I summarized apostabout tips ofSolaris/illumossocket programming before, and you can read it if you happen to work on these platforms.

(5) Leverage sniffer tools.Tcpdump/Wireshark/snoopare amazing tools for debugging network programming, and they can tell you what really happens under the hood. Try to be sophisticated at these tools, and they will save you at one day, trust me!