Foundations of Python Network Programming

(WallPaper) #1

Chapter 7 ■ Server arChiteCture


118


def create_srv_socket(address):
"""Build and return a listening server socket."""
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(address)
listener.listen(64)
print('Listening at {}'.format(address))
return listener


def accept_connections_forever(listener):
"""Forever answer incoming connections on a listening socket."""
while True:
sock, address = listener.accept()
print('Accepted connection from {}'.format(address))
handle_conversation(sock, address)


def handle_conversation(sock, address):
"""Converse with a client over sock until they are done talking."""
try:
while True:
handle_request(sock)
except EOFError:
print('Client socket to {} has closed'.format(address))
except Exception as e:
print('Client {} error: {}'.format(address, e))
finally:
sock.close()


def handle_request(sock):
"""Receive a single client request on sock and send the answer."""
aphorism = recv_until(sock, b'?')
answer = get_answer(aphorism)
sock.sendall(answer)


def recv_until(sock, suffix):
"""Receive bytes over socket sock until we receive the suffix."""
message = sock.recv(4096)
if not message:
raise EOFError('socket closed')
while not message.endswith(suffix):
data = sock.recv(4096)
if not data:
raise IOError('received {!r} then socket closed'.format(message))
message += data
return message


The three questions that a client can expect a server to understand are listed as keys in the aphorisms dictionary,
and their answers are stored as the values. The get_answer() function is a quick shorthand for doing a safe lookup
into this dictionary for an answer, with a short error message returned if the aphorism is not recognized. Note that the
client requests always end with a question mark and that answers—even the fallback error message—always end with
a period. These two pieces of punctuation provide the tiny protocol with its framing.

Free download pdf