Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi Threaded TCP server in Python

Tags:

I have created a simple multi threaded tcp server using python's threding module. This server creates a new thread each time a new client is connected.

#!/usr/bin/env python

import socket, threading

class ClientThread(threading.Thread):

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


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

        clientsock.send("\nWelcome to the server\n\n")

        data = "dummydata"

        while len(data):
            data = clientsock.recv(2048)
            print "Client sent : "+data
            clientsock.send("You sent me : "+data)

        print "Client 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))
threads = []


while True:
    tcpsock.listen(4)
    print "\nListening for incoming connections..."
    (clientsock, (ip, port)) = tcpsock.accept()
    newthread = ClientThread(ip, port)
    newthread.start()
    threads.append(newthread)

for t in threads:
    t.join()

Then I opened two new terminals and connected to the server using netcat. Then, when I type and send my first data to the server using the first terminal I connected, reply from the server comes to the other terminal and first connection got disconnected. I guessed the reason but I am doubtful whether this happens because clientsock variable is overwritten so that it refers to the second connection's socket. Am I correct and then how to avoid that?

Is there a way other than using an array with limited number of socket variables and using each variable for each connection?

like image 256
Deepal Avatar asked Jul 03 '13 16:07

Deepal


People also ask

How do I create a multithreaded server in Python?

Create Python Multi Threaded Server Socket Program (Server.py) and Python Client Socket Program (client.py) in two separate files. Open a DOS prompt (console) and run the Server Program first. Then you will get the message "Server started" in Server side.

Is multi threading possible in Python?

Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library. The GIL does not prevent threading.

What is TCP multithreading?

Multithreading (Contd.) ∎ Multithreading allows a program to perform. multiple tasks concurrently. □ Although threads give the appearance of running. concurrently, in a single- processor system the interpreter is switching between the threads and running them one at a time.


1 Answers

You should pass the client sock to the thread like you do with the ip address and the port:

class ClientThread(threading.Thread):

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

    def run(self):
        # use self.socket to send/receive

...
(clientsock, (ip, port)) = tcpsock.accept()
newthread = ClientThread(ip, port, clientsock)
...
like image 140
mata Avatar answered Sep 19 '22 14:09

mata