Socket Programming with Multi-threading in Python Last Updated : 14 Jul, 2022 Comments Improve Suggest changes Like Article Like Report Prerequisite : Socket Programming in Python, Multi-threading in PythonSocket Programming-> It helps us to connect a client to a server. Client is message sender and receiver and server is just a listener that works on data sent by client.What is a Thread? A thread is a light-weight process that does not require much memory overhead, they are cheaper than processes.What is Multi-threading Socket Programming? port on your computerMultithreading is a process of executing multiple threads simultaneously in a single process.Multi-threading Modules : A _thread module & threading module is used for multi-threading in python, these modules help in synchronization and provide a lock to a thread in use. from _thread import * import threading A lock object is created by-> print_lock = threading.Lock() A lock has two states, "locked" or "unlocked". It has two basic methods acquire() and release(). When the state is unlocked print_lock.acquire() is used to change state to locked and print_lock.release() is used to change state to unlock.The function thread.start_new_thread() is used to start a new thread and return its identifier. The first argument is the function to call and its second argument is a tuple containing the positional list of arguments.Let's study client-server multithreading socket programming by code- Note:-The code works with python3. Multi-threaded Server Code Python3 # import socket programming library import socket # import thread module from _thread import * import threading print_lock = threading.Lock() # thread function def threaded(c): while True: # data received from client data = c.recv(1024) if not data: print('Bye') # lock released on exit print_lock.release() break # reverse the given string from client data = data[::-1] # send back reversed string to client c.send(data) # connection closed c.close() def Main(): host = "" # reserve a port on your computer # in our case it is 12345 but it # can be anything port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("socket binded to port", port) # put the socket into listening mode s.listen(5) print("socket is listening") # a forever loop until client wants to exit while True: # establish connection with client c, addr = s.accept() # lock acquired by client print_lock.acquire() print('Connected to :', addr[0], ':', addr[1]) # Start a new thread and return its identifier start_new_thread(threaded, (c,)) s.close() if __name__ == '__main__': Main() Console Window: socket binded to port 12345 socket is listening Connected to : 127.0.0.1 : 11600 Bye Client Code Python # Import socket module import socket def Main(): # local host IP '127.0.0.1' host = '127.0.0.1' # Define the port on which you want to connect port = 12345 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # connect to server on local computer s.connect((host,port)) # message you send to server message = "shaurya says geeksforgeeks" while True: # message sent to server s.send(message.encode('ascii')) # message received from server data = s.recv(1024) # print the received message # here it would be a reverse of sent message print('Received from the server :',str(data.decode('ascii'))) # ask the client whether he wants to continue ans = input('\nDo you want to continue(y/n) :') if ans == 'y': continue else: break # close the connection s.close() if __name__ == '__main__': Main() Console Window: Received from the server : skeegrofskeeg syas ayruahs Do you want to continue(y/n) :y Received from the server : skeegrofskeeg syas ayruahs Do you want to continue(y/n) :n Process finished with exit code 0 Reference-> https://docs.python.org/2/library/thread.html Comment More infoAdvertise with us Next Article Socket Programming with Multi-threading in Python S SHAURYA UPPAL Improve Article Tags : Misc Python Computer Networks Practice Tags : Miscpython Similar Reads Python Tutorial | Learn Python Programming Language Python Tutorial â 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.Python is:A high-level language, used in web development, data science, automatio 10 min read What is OSI Model? - Layers of OSI Model The OSI (Open Systems Interconnection) Model is a set of rules that explains how different computer systems communicate over a network. OSI Model was developed by the International Organization for Standardization (ISO). The OSI Model consists of 7 layers and each layer has specific functions and re 13 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 SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e 7 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 TCP/IP Model The TCP/IP model (Transmission Control Protocol/Internet Protocol) is a four-layer networking framework that enables reliable communication between devices over interconnected networks. It provides a standardized set of protocols for transmitting data across interconnected networks, ensuring efficie 7 min read Types of Network Topology Network topology refers to the arrangement of different elements like nodes, links, or devices in a computer network. Common types of network topology include bus, star, ring, mesh, and tree topologies, each with its advantages and disadvantages. In this article, we will discuss different types of n 12 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 Like