nettux443 nettux443 - 1 year ago 88
Python Question

How to make a simple multithreaded socket server in Python that remembers clients

How do I make a simple Python echo server that remembers clients and doesn't create a new socket for each request? Must be able to support concurrent access. I want to be able to connect once and continually send and receive data using this client or similar:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("Server hostname or ip? ")
port = input("Server port? ")
while True:
data = raw_input("message: ")
print "response: ", sock.recv(1024)

I.e. with the server running on port 50000, using the above client I want to be able to do this:

Server hostname or ip? localhost
Server Port? 50000
message: testa
response: testa
message: testb
response: testb
message: testc
response: testc

Answer Source

You can use a thread per client to avoid the blocking client.recv() then use the main thread just for listening for new clients. When one connects, the main thread creates a new thread that just listens to the new client and ends when it doesn't talk for 60 seconds.

import socket
import threading

class ThreadedServer(object):
    def __init__(self, host, port): = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((, self.port))

    def listen(self):
        while True:
            client, address = self.sock.accept()
            threading.Thread(target = self.listenToClient,args = (client,address)).start()

    def listenToClient(self, client, address):
        size = 1024
        while True:
                data = client.recv(size)
                if data:
                    # Set the response to echo back the recieved data 
                    response = data
                    raise error('Client disconnected')
                return False

if __name__ == "__main__":
    port_num = input("Port? ")

Clients timeout after 60 seconds of inactivity and must reconnect. See the line client.settimeout(60) in the function ThreadedServer.listen()