The socket factory function creates a new socket of the
given type (in this case, an Internet stream socket, also known as
a TCP socket). The connect method attempts to connect this
socket to the given server. Once that has succeeded, the
recv method is used to read data.

Creating a server socket is done in a similar fashion. But
instead of connecting to a server, you bind the socket to
a port on the local machine, tell it to listen for
incoming connection requests, and process each request as fast as
possible.

The following example creates a time server, bound to port 8037
on the local machine (port numbers up to 1024 are reserved for
system services, and you have to have root privileges to use them
to implement services on a Unix system):

The listen call tells the socket that we’re willing to
accept incoming connections. The argument gives the size of the
connection queue (which holds connection requests that our program
hasn’t gotten around to processing yet). Finally, the
accept loop returns the current time to any client bold
enough to connect.

Note that the accept function returns a new socket
object, which is directly connected to the client. The original
socket is only used to establish the connection; all further
traffic goes via the new socket.

To test this server, we can use the following generalized
version of our first example:

This sample script can also be used as a module; to get the
current time from a server, import the timeclient module,
and call the gettime function.

This far, we’ve used stream (or TCP) sockets. The time protocol
specification also mentions UDP sockets, or datagrams. Stream
sockets work pretty much like a phone line; you’ll know if someone
at the remote end picks up the receiver, and you’ll notice when she
hangs up. In contrast, sending datagrams is more like shouting into
a dark room. There might be someone there, but you won’t know
unless she replies.

You don’t need to connect to send data over a datagram socket.
Instead, you use the sendto method, which takes both the
data and the address of the receiver. To read incoming datagrams,
use the recvfrom method.