BYUBRIGHAM YOUNG UNIVERSITY
Computer Science
Python Network Programming

The Socket Module

Catching Exceptions

In the previous examples, we have not checked for any exceptions that could be raised by methods in the socket module. One clear example is when the server tries to bind its socket to a particular port. Only one process is allowed to bind to each port; if this port is already being used then an exception is raised.

Here is the modified echo server that catches some of these exceptions (echoserver-simple-exceptions.py):

#!/usr/bin/env python

"""
A simple echo server that handles exceptions
"""

import socket

host = ''
port = 50000
backlog = 5
size = 1024
s = None
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host,port))
    s.listen(backlog)
except socket.error, (value,message):
    if s:
        s.close()
    print "Could not open socket: " + message
    sys.exit(1)
while 1:
    client, address = s.accept()
    data = client.recv(size)
    if data:
        client.send(data)
    client.close()

The part that has changed is where the socket is initialized:

s = None
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host,port))
    s.listen(backlog)
except socket.error, (value,message):
    if s:
        s.close()
    print "Could not open socket: " + message
    sys.exit(1)

This code is surrounded by a try-except statement, and the except portion contains two values: the socket.error exception, and its return value. The socket.error exception is raised for socket-related errors; the socket module defines several other exceptions for address-related errors. The return value of the socket is a tuple consisting of an error code and message.

Try running this server twice, and the second time you should be able to see the exception that is caught. Run the original server twice if you want to see what happens when the exception is not caught.

As another example, here is the echo client modified to catch some exceptions (echoclient-simple-exceptions.py):

#!/usr/bin/env python

"""
A simple echo client that handles some exceptions
"""

import socket
import sys

host = 'localhost'
port = 50000
size = 1024
s = None
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host,port))
except socket.error, (value,message):
    if s:
        s.close()
    print "Could not open socket: " + message
    sys.exit(1)
s.send('Hello, world')
data = s.recv(size)
s.close()
print 'Received:', data

Try running this version (and the original) without running the server at all, and see the exception that is caught.