Learning Python Network Programming

(Sean Pound) #1

Client and Server Applications


Notice that recv 1 and recv 2, when taken together contain a complete message,
but they also contain the beginning of the next message. Clearly, we need to update
our parsing. One option is to read data from the socket one byte at a time, that is, use
recv(1), and check every byte to see if it's a null byte. This is a dismally inefficient
way to use a network socket though. We want to read as much data in our call to
recv() as we can. Instead, when we encounter an incomplete message we can cache
the extraneous bytes and use them when we next call recv(). Lets do this, add these
functions to the tincanchat.py file:


def parse_recvd_data(data):
""" Break up raw received data into messages, delimited
by null byte """
parts = data.split(b'\0')
msgs = parts[:-1]
rest = parts[-1]
return (msgs, rest)

def recv_msgs(sock, data=bytes()):
""" Receive data and break into complete messages on null byte
delimiter. Block until at least one message received, then
return received messages """
msgs = []
while not msgs:
recvd = sock.recv(4096)
if not recvd:
raise ConnectionError()
data = data + recvd
(msgs, rest) = parse_recvd_data(data)
msgs = [msg.decode('utf-8') for msg in msgs]
return (msgs, rest)

From now on, we'll be using recv_msgs() wherever we were using recv_msg()
before. So, what are we doing here? Starting with a quick scan through recv_msgs(),
you can see that it's similar to recv_msg(). We make repeated calls to recv() and
accumulate the received data as before, but now we will be using parserecvd
data() to parse it, with the expectation that it may contain multiple messages. When
parse_recvd_data() finds one or more complete messages in the received data,
it splits them into a list and returns them, and if there is anything left after the last
complete message, then it additionally returns this using the rest variable. The
recv_msgs() function then decodes the messages from UTF-8, and returns them
and the rest variable.

Free download pdf