Python Socket Server Example

We already know how to check host availability by ping, but that is not good enough. The file returned by popen() is often unreadable. And we need actual communication between client and server side. This is about how to create a simple server with Python socket.

First the class of server. It is a open-ended thread can run forever.  It always listens and waits for a client to contact. Once a connection is established, it tries to receive any message sent by client, then reply a ‘roger’. As soon as the current connection is severed, it comes back to listening again.

import socket, datetime, threading, os

class AServer(threading.Thread):
    def __init__(self, port):
        threading.Thread.__init__(self)
        self.port = port

    def now(self):
        d = datetime.datetime.now()
        return d.strftime("%d/%m/%y %H:%M:%S")

    def run(self):
        host = ''
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host, self.port))
        print 'server started successfully, waiting...'
        s.listen(1)
        conn, addr = s.accept()
        print 'contact', addr, 'on', self.now()

        while 1:
            try:
                data = conn.recv(1024)
            except socket.error:
                print 'lost', addr, 'waiting..'
                s.listen(1)
                conn, addr = s.accept()
                print 'contact', addr, 'on', self.now()
                continue

            if not data:
                print 'lost', addr, 'waiting..'
                s.listen(1)
                conn, addr = s.accept()
                print 'contact', addr, 'on', self.now()
            else:    
                print "received msg:", data
                conn.send('roger')

To start the server on local host at a given port:

 t = AServer(31944)
 t.start()

Now write a simple client to contact the server, make sure the host address and port is set correctly:

import socket, time, threading, sys

host = '127.0.0.1'
port = 31944

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(3.0)
try:
    s.connect((host,port))
except socket.error:
    print host ,'is offline, stop '
    exit()

try:
    s.send('hello')
    data = s.recv(1024)
    print host, 'says:', data
except socket.error:
    print host,'is offline, stop '
    exit()

s.close()

As long as the server side is running, this will always get a ‘roger’. Because the client exit() right after receiving the first message from server. It will immediately be lost on the server side.

Advertisements

Leave a comment

Filed under Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s