Information Security, Web, Networks and Systems

Wednesday, July 3, 2013

Hacker's Python 3 - Multi Threaded TCP Echo server in Python

10:32 AM Posted by Deepal Jayasekara , , , , 3 comments
I have created a simple Multi - Threaded ECHO server in python. We can create it using python's socket and threading modules. This server listens for port 9999 of all interfaces.When started this server runs with a single thread and listens for an incoming connection. When a client tries to connect, this server creates a new thread to handle that connection. So multiple clients can communicate with the server with each client corresponds to a particular thread of the server.

A problem I met with in this was, when two clients are connected one after another, reference to the first client's socket gets replaced with the second client's socket. I have solved that problem by passing reference of the clientsock variable to the new object of ClientThread which represents the new client connected.

You can get an understanding how a multithreaded tcp server works by this script. I hope to create a simple chat server which gets data from a client and broadcasts to all other clients connected. See you soon.

You can download the source code here

#!/usr/bin/env python

import socket, threading

class ClientThread(threading.Thread):

    def __init__(self,ip,port,clientsocket):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.csocket = clientsocket
        print "[+] New thread started for "+ip+":"+str(port)

    def run(self):    
        print "Connection from : "+ip+":"+str(port)

        clientsock.send("nWelcome to the servernn")

        data = "dummydata"

        while len(data):
            data = self.csocket.recv(2048)
            print "Client(%s:%s) sent : %s"%(self.ip, str(self.port), data)
            self.csocket.send("You sent me : "+data)

        print "Client at "+self.ip+" disconnected..."

host = "0.0.0.0"
port = 9999

tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

tcpsock.bind((host,port))

while True:
    tcpsock.listen(4)
    print "nListening for incoming connections..."
    (clientsock, (ip, port)) = tcpsock.accept()

    #pass clientsock to the ClientThread thread object being created
    newthread = ClientThread(ip, port, clientsock)
    newthread.start()

3 comments:

  1. Shouldn't
    clientsock.send("nWelcome to the servernn")
    be
    self.csocket.send("nWelcome to the servernn")

    ReplyDelete
    Replies
    1. You are correct. Using clientsock.send() also works in this situation since its value is set before being accessed by ClientThread instance. But using self.csocket.send() is more intuitive. Thanks a lot for pointing out that! I'll update the post.

      Delete
  2. Excellent solution to the problem when two clients are connected to each other, the reference to the first client socket is replaced by the second client terminal. I appreciate it, that's cool!
    Server operating principle is clear he is somewhat similar to the work of the cloud server vdr virtual data room

    ReplyDelete

Note: Only a member of this blog may post a comment.