Transmission Control Protocol, or TCP for short, is a connection-oriented protocol allowing peers to exchange streams of data. Unlike UDP, with TCP package reception is guaranteed and packages are received in the same order they are sent. Common uses of TCP include HTTP requests, peer-to-peer applications, and IM client/server connections. Erlang distribution is built on top of TCP. Just as with UDP, neither the client nor the server has to be implemented in Erlang.
On an architectural level, the main difference between TCP and UDP is that once you’ve opened a socket connection using TCP, it is kept open until either side closes it or it terminates because of an error. When setting up a connection, you would often spawn a new process for every request, keeping it alive for as long as the request is being handled.
How does this work in practice? Say you have a listener process whose task is to wait for incoming TCP requests. As soon as a request comes in, the process that acknowledges the connection request becomes the accept process. There are two mechanisms for defining the accept process:
The first option is to spawn a new process which becomes the accept process, while the listener goes back and listens for a new connection request.
The second option, as shown in Figure 15-2, is to make the listener process the accept process, and spawn a new process which becomes the new listener.
Figure 15-2. The listener and accept processes
If the socket is opened ...