Multithreaded socket server in Python

A thread embodies a sequential set of instructions within a program, capable of autonomous execution irrespective of surrounding code. In the context of a multithreaded program, it encompasses the coexistence of two or more discrete segments, capable of concurrent operation. Each constituent element of this program is denoted as a thread, each threading its unique course of execution. The paradigm of Multithreaded Socket Programming elucidates the capacity of a Multithreaded Socket Server to establish simultaneous communication with multiple clients, all within the same network environment.

Python Multithreaded Socket Programming

In the prior lesson, we explored Python Socket Programming , wherein we learned that a Server Socket Program had the capacity to interact with a sole client exclusively at any given point. This intrinsic limitation implied that the Python Server Socket Program remained incapable of accommodating connections from multiple clients concurrently. As we transition to the subsequent section, we will investigate into the mechanics of how a Python Multithreaded Server can adeptly establish communication with numerous clients concurrently.

Prior to explore into this section, it is highly recommended to revisit the foundational principles of Socket Programming as elucidated in the preceding lesson. This will provide a comprehensive understanding of the context before immersing into the upcoming content.

Python Multithreaded Socket Programming has two sections:

  1. Python Multi Threaded Server Socket Program (Server.py)
  2. Python Client Socket Program (client.py)
Multithreaded Server Socket Example (Server.py)
import socket, threading class ClientThread(threading.Thread): def __init__(self,clientAddress,clientsocket): threading.Thread.__init__(self) self.csocket = clientsocket print ("New connection added: ", clientAddress) def run(self): print ("Connection from : ", clientAddress) #self.csocket.send(bytes("Hi, This is from Server..",'utf-8')) msg = '' while True: data = self.csocket.recv(2048) msg = data.decode() if msg=='bye': break print ("from client", msg) self.csocket.send(bytes(msg,'UTF-8')) print ("Client at ", clientAddress , " disconnected...") LOCALHOST = "127.0.0.1" PORT = 8080 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((LOCALHOST, PORT)) print("Server started") print("Waiting for client request..") while True: server.listen(1) clientsock, clientAddress = server.accept() newthread = ClientThread(clientAddress, clientsock) newthread.start()
Python Socket Client Example(client.py)
import socket SERVER = "127.0.0.1" PORT = 8080 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((SERVER, PORT)) client.sendall(bytes("This is from Client",'UTF-8')) while True: in_data = client.recv(1024) print("From Server :" ,in_data.decode()) out_data = input() client.sendall(bytes(out_data,'UTF-8')) if out_data=='bye': break client.close()

How to run this program ?

Develop a Python Multi-Threaded Server Socket Program (server.py) and a corresponding Python Client Socket Program (client.py), segregating them into distinct files. Initiate a Command Prompt (console) and commence execution with the Server Program as the initial step. Subsequently, an acknowledgment message of "Server started" will manifest on the Server side.

Following this, launch the Client program within a separate Command Prompt (console), facilitating the reception of messages from the Server. In this manner, you can seamlessly initiate multiple client instances concurrently from disparate Command Prompts, thereby developing interactions with the Server program. The Server graciously accepts incoming messages and promptly reciprocates the identical message back to the originating client. This iterative process can be replicated with multiple client instances, each undergoing independent testing of the Server's responsiveness.

Conclusion

A multithreaded socket server in Python enables concurrent communication with multiple clients by utilizing separate threads for each client connection. This approach enhances the server's efficiency by allowing parallel processing of client requests, resulting in improved responsiveness and streamlined interactions within a network environment.