Computer Networking — Socket interface in Python

In this lab we use the socket interface with Python. You may need to follow along with the instructor.

A non-networked Python program

Let’s start with the following Python 3 program that implements the fetch and add operator.

""" Terminal line program for fetch-and-add """
__author__ = "brock"

class FetchAndAdd(object):
    """ fetch-and-add """
    def __init__(self, initial=0):
        self._value = initial
    def add(self, incr):
        """ the add instruction """
        retv = self._value
        self._value = retv + incr
        return retv
    def __str__(self):
        return str(self._value)

def main():
    """ main routine """
    fad = FetchAndAdd()
    try:
        while 1:
            try:
                incr = int(input('Enter next number: '))
                print('  --> {0}'.format(fad.add(incr)))
            except ValueError:
                print('!!!!')
    except (EOFError, KeyboardInterrupt):
        pass

if __name__ == "__main__":
    main()

For a few minutes, pause and ponder this Python program.

You can edit this program with a ordinary text editor, such as gedit, or you can try out the idle or charm (if installed) IDE. (The instructor uses emacs. I would not recommend that.)

In any case, store the program under the filename fetadd.py .

Running the program

You can run the program with the following command.

[…]$ python fetadd.py

A diversion

Before plunging into fetch-and-add, take a look at the Python 2 socket interface documentation. (If you are brave, you can try Python 3.)

Make your way down to section 17.2.2 and look at the example client and server programs. (It’s section 18.1.5 for Python 3.)

Just wait a minute

Stop for a minute and listen to the instructor explain the Berkeley socket interface. You will not believe it!

Now find a partner. One of you should run the server and the other should run the client. Be sure to modify the client program to use the server’s hostname.

Making a fetch-and-add server

It wouldn’t be that hard to make a fetch-and-add client, but we would need a fetch-and-add server to test. So we are going to do the server first.

This is going to be an old-fashion C-style Berkely sockets implementation. The sockets interface is awful, but everyone uses it at some level.

Back on track

Turn your fetch-and-add terminal program into a fetch-and-add server. You can then use the nc program to test it.

It’s not that hard. You do have to add the import and all of those socket method calls. There is one small complication: When you send a response, you must add a CRLF sequence to confirm to the standards of the 1980’s. This means that a line like
                print('!!!!')
must be replaced with one like
                conn.sendall("!!!!\r\n")

This is a pathetic server. It can only handle one connection at a time. Next week, we’ll take a look at the SocketServer interface.