Socket Programming with Multi-threading in Python Last Updated : 20 Jun, 2025 Summarize Comments Improve Suggest changes Share Like Article Like Report Prerequisite : Socket Programming in Python, Multi-threading in PythonWe are given a scenario where we need to handle multiple client connections to a server simultaneously. This can be achieved using socket programming along with multi-threading. Socket programming allows two machines to communicate with each other over a network, and multi-threading ensures that the server can handle multiple clients at the same time without blocking. For example, if multiple users try to send messages to a server that simply returns the reversed version of their message, we want all of them to get responses immediately without waiting for others to finish. This can be implemented by combining sockets and threads.What is a Socket?A socket in Python is an endpoint in a two-way communication link between two programs running on the network. It is used to send and receive data between a client and a server over a specific port. What is Multi-threading?A thread is a lightweight unit of a process. Multi-threading refers to the ability of a CPU (or a single process) to provide multiple threads of execution concurrently. In socket programming, this allows each client to be handled independently in its own thread.Why Use Multi-threading in Socket Programming?To serve multiple clients simultaneously without blockingTo improve responsiveness of the serverTo separate logic per client (e.g., each client runs its session in parallel)Multi-threaded Server CodeBelow is the server code that uses sockets and multi-threading to handle multiple client connections. Each client gets its own thread, and the server sends back the reversed message received from the client. Python import socket from _thread import start_new_thread import threading lock = threading.Lock() def handle_client(c): while True: data = c.recv(1024) if not data: print('Bye') lock.release() break c.send(data[::-1]) c.close() def main(): host = '' port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) print("Server running on port", port) while True: c, addr = s.accept() lock.acquire() print('Connected to:', addr[0], ':', addr[1]) start_new_thread(handle_client, (c,)) if __name__ == '__main__': main() Output:Console Window:socket binded to port 12345socket is listeningConnected to : 127.0.0.1 : 11600ByeExplanation:s.listen(5) server listens for up to 5 queued connections.start_new_thread(handle_client, (c,)) starts a new thread for each client.lock.acquire() / lock.release() controls access to shared output (like print), avoiding jumbled prints.Multi-threaded Client Code This is the client-side script that connects to the server, sends a message, and prints the reversed message received from the server. The client can continue sending messages until they choose to stop. Python import socket def main(): host = '127.0.0.1' port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) msg = "hello from client" while True: s.send(msg.encode('ascii')) data = s.recv(1024) print('Received from server:', data.decode('ascii')) ans = input('Do you want to continue (y/n): ') if ans.lower() != 'y': break s.close() if __name__ == '__main__': main() Output:Received from server: tneilc morf ollehDo you want to continue (y/n): yReceived from server: tneilc morf ollehDo you want to continue (y/n): nExplanation:s.connect((host, port)) connects to the server at the given IP and port.s.send(msg.encode('ascii')): sends the message to the server in byte format.s.recv(1024) receives the reversed message from the server.The loop continues until the user inputs n. Comment More infoAdvertise with us Next Article Socket Programming with Multi-threading in Python S Shaurya Uppal Improve Article Tags : Python Practice Tags : python Similar Reads Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo 10 min read Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth 15+ min read Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p 11 min read Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list 10 min read Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test 9 min read Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co 11 min read Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien 3 min read Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes 9 min read Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is 8 min read Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam 3 min read Like