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 Socket Programming in Python Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the serv 6 min read Output of Python program | Set 16 (Threads) 1) What is the output of the following program? Python import threading barrier = threading.Barrier(4) class thread(threading.Thread): def __init__(self, thread_ID, thread_name): threading.Thread.__init__(self) self.thread_ID = thread_ID self.thread_name = thread_name def run(self): print("Thre 3 min read Threaded Port Scanner using Sockets in Python Port scanning can be really slow yet, in most cases, is not process intensive. Thus, we can use threading to improve our speed. There can be thousands of possible ports. If it takes 5-15 seconds per port to scan, then we might have a long wait ahead of us without the use of threading. Threading Thre 2 min read Multithreading in Python | Set 2 (Synchronization) This article discusses the concept of thread synchronization in case of multithreading in Python programming language. Synchronization between threads Thread synchronization is defined as a mechanism which ensures that two or more concurrent threads do not simultaneously execute some particular prog 6 min read Simple Calculator in Python Socket Programming In this article, we are going to know how to make a simple calculator in Python socket programming. Prerequisite: Socket Programming in Python. First, we will understand the basics of Python socket programming. Socket programming is used to set up a communication channel between two nodes on a netwo 4 min read Running Queries in Python Using Multiprocessing Before diving into running queries using multiprocessing letâs understand what multiprocessing is in Python. Multiprocessing enables the computer to utilize multiple cores of a CPU to run tasks/processes in parallel. This parallelization leads to significant speedup in tasks that involve a lot of co 3 min read Multithreading or Multiprocessing with Python and Selenium Multithreading and multiprocessing are two popular approaches for improving the performance of a program by allowing it to run tasks in parallel. These approaches can be particularly useful when working with Python and Selenium, as they allow you to perform multiple actions simultaneously, such as a 11 min read Python - Binding and Listening with Sockets Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. 3 min read Network Programming Python - HTTP Server HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request. Python has a built-in webserver provided by its standard library, can be called for simple client-server communication. 3 min read Python | Communicating Between Threads | Set-2 Prerequisite: Communicating Between Threads | Set-1 If a thread needs to know immediately when a consumer thread has processed a particular item of data, one should pair the sent data with an Event object that allows the producer to monitor its progress as shown in the code given below - Code #1 : P 4 min read Like