Learning Python Network Programming

(Sean Pound) #1

Client and Server Applications


def prep_msg(msg):
""" Prepare a string to be sent as a message """
msg += '\0'
return msg.encode('utf-8')

def send_msg(sock, msg):
""" Send a string over a socket, preparing it first """
data = prep_msg(msg)
sock.sendall(data)

First we define a default interface and a port number to listen on. The empty ''
interface, specified in the HOST variable, tells socket.bind() to listen on all available
interfaces. If you want to restrict access to just your machine, then change the value
of the HOST variable at the beginning of the code to 127.0.0.1.


We'll be using create_listen_socket() to set up our server listening connections.
This code is the same for several of our server programs, so it makes sense to reuse it.


The recv_msg() function will be used by our echo server and client for receiving
messages from a socket. In our echo protocol, there isn't anything that our programs
may need to do while they're waiting to receive a message, so this function just calls
socket.recv() in a loop until it has received the whole message. As per our framing
rule, it will check the accumulated data on each iteration to see if it has received a
null byte, and if so, then it will return the received data, stripping off the null byte
and decoding it from UTF-8.


The send_msg() and prep_msg() functions work together for framing and sending
a message. We've separated the null byte termination and the UTF-8 encoding into
prep_msg() because we will use them in isolation later on.


Handling the received data


Note that we're drawing ourselves a careful line with these send and receive
functions as regards string encoding. Python 3 strings are Unicode, while the data
that we receive over the network is bytes. The last thing that we want to be doing
is handling a mixture of these in the rest of our program code, so we're going to
carefully encode and decode the data at the boundary of our program, where the
data enters and leaves the network. This will ensure that any functions in the rest of
our code can assume that they'll be working with Python strings, which will later on
make things much easier for us.

Free download pdf