Simple Network Server Part 2

Created on: 2015-11-07 19:00:00 -0500

Categories: Network Applications


In my last tutorial I went over how to set up a quick server to help in network centric application development. We went over how to set up Netcat to act as a simple echo server. In this tutorial we will go over how to use Python to set up an echo server. Python makes prototyping development very fast with less than 20 lines of code you can quickly set up an echo server.

In this first example we will setup a UDP based echo server. The code we will use is shown below and is available from my github repo file named udpSimpleServer.py

import socket

IP = '127.0.0.1';
PORT = 8088;

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
sock.bind((IP, PORT));

while True:
        data, addr = sock.recvfrom(1024);
        print "data: ",data
        sock.sendto("Server> " + data, addr)

To run the code from command line simple issue the following command:

$ python udpSimpleServer.py

In another console window use Netcat to access the server localhost 8088. Enter in a line and press enter to have the server echo back the line.

$ nc -4u localhost 8088
This is a test
Server> This is test

From the server side you will see the following:

$ python udpSimpleServer.py 
data:  This is test

You can kill both processes using Ctrl-C . The next code illustrates how to do the same using TCP as the transport. This file is also available from the github repo as tcpSimpleServer.py.

import socket

IP = '127.0.0.1';
PORT = 8088;

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
sock.bind((UDP_IP, UDP_PORT));
sock.listen(1);

while True:
        client, addr = sock.accept();
        while True:
                data = client.recv(1024);
                print "data: ",data;
                client.send("Server>" + data);
                if not data:
                        break;

        client.close();

You can run it by using the following command:

$ python tcpSimpleServer.py

Then telnet to it as shown in the example.

$ telnet localhost 8088
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
This is a tests
Server>This is a tests
^]
telnet> close
Connection closed.

The server side will look like the following.

$ python tcpSimpleServer.py 
data:  This is a tests

If you need to change the IP address to access the server from another computer simply change the IP lines in either code and run the server. Remember to add the firewall rules to allow network access to the server.

While this solution is not so elegant it will quickly get you up to speed with testing and troubleshooting your network application. In the future the two applications will be merged into a more elegant application.