Learning Python Network Programming

(Sean Pound) #1
Chapter 8

Of course, not all the data that we may want to send or receive over a network will
be text. For example, images, compressed files, and music, can't be decoded to a
Unicode string, so a different kind of handling is needed. Usually this will involve
loading the data into a class, such as a Python Image Library (PIL) image for
example, if we are going to manipulate the object in some way.


There are basic checks that could be done here on the received data, before
performing full processing on it, to quickly flag any problems with the data.
Some examples of such checks are as follows:



  • Checking the length of the received data

  • Checking the first few bytes of a file for a magic number to confirm a file type

  • Checking values of higher level protocol headers, such as the Host header in
    an HTTP request


This kind of checking will allow our application to fail fast if there is an
obvious problem.


The server itself


Now, let's write our echo server. Open a new file called 1.1-echo-server-uni.py
and save the following code in it:


import tincanchat

HOST = tincanchat.HOST
PORT = tincanchat.PORT

def handle_client(sock, addr):
""" Receive data from the client via sock and echo it back """
try:
msg = tincanchat.recv_msg(sock) # Blocks until received
# complete message
print('{}: {}'.format(addr, msg))
tincanchat.send_msg(sock, msg) # Blocks until sent
except (ConnectionError, BrokenPipeError):
print('Socket error')
finally:
print('Closed connection to {}'.format(addr))
sock.close()
Free download pdf