value of 5 is usually enough for most socket-based programs; the value must be at
least 1.
At this point, the server is ready to accept connection requests from client programs
running on remote machines (or the same machine) and falls into an infinite loop—
while True (or the equivalent while 1 for older Pythons and ex-C programmers)—
waiting for them to arrive:
connection, address = sockobj.accept()
Waits for the next client connection request to occur; when it does, the accept call
returns a brand-new socket object over which data can be transferred from and to
the connected client. Connections are accepted on sockobj, but communication
with a client happens on connection, the new socket. This call actually returns a
two-item tuple—address is the connecting client’s Internet address. We can call
accept more than one time, to service multiple client connections; that’s why each
call returns a new, distinct socket for talking to a particular client.
Once we have a client connection, we fall into another loop to receive data from the
client in blocks of up to 1,024 bytes at a time, and echo each block back to the client:
data = connection.recv(1024)
Reads at most 1,024 more bytes of the next message sent from a client (i.e., coming
across the network or IPC connection), and returns it to the script as a byte string.
We get back an empty byte string when the client has finished—end-of-file is trig-
gered when the client closes its end of the socket.
connection.send(b'Echo=>' + data)
Sends the latest byte string data block back to the client program, prepending the
string 'Echo=>' to it first. The client program can then recv what we send here—
the next reply line. Technically this call sends as much data as possible, and returns
the number of bytes actually sent. To be fully robust, some programs may need to
resend unsent portions or use connection.sendall to force all bytes to be sent.
connection.close()
Shuts down the connection with this particular client.
Transferring byte strings and objects
So far we’ve seen calls used to transfer data in a server, but what is it that is actually
shipped through a socket? As we learned in Chapter 5, sockets by themselves always
deal in binary byte strings, not text. To your scripts, this means you must send and will
receive bytes strings, not str, though you can convert to and from text as needed with
bytes.decode and str.encode methods. In our scripts, we use b'...' bytes literals to
satisfy socket data requirements. In other contexts, tools such as the struct and
pickle modules return the byte strings we need automatically, so no extra steps are
needed.
Socket Programming | 791