Table of contents
1.
Introduction
1.1.
Socket Programming
1.2.
Threads
1.3.
Multithreading
1.4.
Multithreading in Python
2.
Socket programming with multithreading in Python
3.
Frequently asked questions
3.1.
Differentiate between multiprocessing and multithreading.
3.2.
Can a single server have multiple client connections?
3.3.
Differentiate between a port and a socket.
3.4.
How many types of sockets are available to design?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Socket Programming with Multithreading in Python

Introduction

Socket programming refers to the method by which two nodes interact with one another on a network via a listening server. In the real scenario, we have more than two clients needing to communicate simultaneously over the network, increasing the server's overhead. There are some ways to optimize the situation, and one of them is using multithreading.

This article will help you understand how we can set up a multithreaded architecture in socket programming to optimize the nodes' communication over the network.

We will help you understand the basics of Python's socket programming, threads, and multithreading concepts. We will also demonstrate how you can implement socket programming with multithreading in Python.

Socket Programming

Socket programming is a method of allowing two network nodes to interact with one another. One socket (node) waits on a specific port at an IP(Internet Protocol) address while the other socket establishes a connection with it. The server creates the listener socket while the client connects to the server.

Learn more about Fibonacci Series in Python on Code Studio.

Socket programming is the true foundation of web navigation. We will learn more about implementing socket programming with multithreading in Python in the coming sections.

Threads

A thread is a fundamental unit of CPU usage, consisting of a thread ID, a program counter, a register, and a stack.'

A process that contains many threads is known as a 'multithreaded' process. The code, data, files, and signals are shared throughout these numerous threads.

Learn more about threads on Code Studio.

Multithreading

Multithreading refers to a processor's capacity to run many threads simultaneously.

It is accomplished with a primary single-core CPU by switching between threads often. Context switching is the name for this. When a thread is interrupted (due to I/O or explicitly set), its state is stored, and another thread is loaded. Context switching occurs so often that all threads appear to be executing simultaneously (termed multitasking).

Learn about multithreading models and multithreading advantages on our blog vertical Library.

Multithreading in Python

Python's threading module provides a relatively simple and obvious API(Application Programming Interface) for generating numerous threads in an application.

Consider the following example, which makes use of the threading module:

Code

import threading
 def print_cube(number):
   """
   this function prints a cube of a num
   """
   print("Cube of number: {}".format(number * number * number))
 def print_square(number):
   """
   this function prints square of a num
   """
   print("Square of number: {}".format(number * number))
 if __name__ == "__main__":
   # Creating threads
   thread1 = threading.Thread(target=print_square, args=(4,))
   thread2 = threading.Thread(target=print_cube, args=(4,))

   # Starting thread 1
   thread1.start()

   # Starting thread 2
   thread2.start()

    # Wait until thread 1 is completely executed
   thread1.join()

   # Wait until thread 2 is completely executed
   thread2.join()

   # Both threads entirely executed
   print("Executed after Thread 1 and Thread 2")
You can also try this code with Online Python Compiler
Run Code

 

Output

Square of number: 16 
Cube of number: 64 
Executed after Thread 1 and Thread 2
You can also try this code with Online Python Compiler
Run Code

 

You can compile it with online python compiler.

Python includes two modules that help programmers implement threads.

  • Threading module 
  • thread (for Python 2.x) or _thread (for Python 3.x).

The threading module provides an object-oriented way of creating a thread, whereas the thread module produces a thread as a function.

We will now learn how to integrate the above two concepts using socket programming with Multithreading in Python

Related Article Multithreading Operating System, Swapcase in Python

Socket programming with multithreading in Python

Let's look into client-server socket programming with multithreading in Python by the implementation.

Server Code

# Import socket programming library
import socket

# Import thread module and threading library
from _thread import *
import threading

print_lock = threading.Lock()

# Threaded function
def threaded(client):
   while True:

       # Data is received from the client
       data = client.recv(1001)
       if not data:
           print('No connection, Bye')
          
           # Releasing lock on exit
           print_lock.release()
           break

       # Reverse the given string from the client
       data = data[::-1]

       # Send back reversed string to the client
       client.send(data)

   # Connection closed
   client.close()


def main():
   host = ""

   # Reverse a port on the computer
   # In the case it is 2002 but it can be anything
   port = 2002
   server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   server.bind((host, port))
   print("socket bond to port", port)

   # Put the socket into listening mode
   server.listen(5)
   print("socket is listening")

   # An infinite loop until the client exits
   while True:

       # Establish connection with client
       c, addr = server.accept()

       # Lock acquired by client
       print_lock.acquire()
       print('Connected to :', addr[0], ':', addr[1])

       # Start the new thread and return its identifier
       start_new_thread(threaded, (c,))
   server.close()


if __name__ == '__main__':
   main()
You can also try this code with Online Python Compiler
Run Code

 

Output

socket bound to port 2002
socket is listening
Connected to : 127.0.0.1 : 11554
No connection, Bye
You can also try this code with Online Python Compiler
Run Code

You can compile it with online python compiler.

 

Client Code

# Import socket module
import socket

def main():
   # Local host IP '127.0.0.1'
   host = '127.0.0.1'

   # Define the server port to connect with
   port = 2002

   server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

   # Connect to server on local computer
   server.connect((host,port))

   # String you want to send to server
   message = "Go Coding Ninjas."
   while True:

       # Message sent to server
       server.send(message.encode('ascii'))

       # Message received from server
       data = server.recv(1001)

       # Print the received message from server
       print('Received message from the server :',str(data.decode('ascii')))

       cont= input('\nDo you want to continue(y/n) :')
       if cont== 'y':
           continue
       else:
           break
   # Close the connection
   server.close()

if __name__ == '__main__':
   main()
You can also try this code with Online Python Compiler
Run Code

 

Output

Received from the server : .sajniN gnidoC oG

Do you want to continue(y/n) :y
Received from the server : .sajniN gnidoC oG

Do you want to continue(y/n) :n
You can also try this code with Online Python Compiler
Run Code

 

As a result, threads are among the most frequent methods for dealing with many socket connections and clients.

Check out this article - Quicksort Python.

Must Read Invalid Syntax in Python.

Frequently asked questions

Differentiate between multiprocessing and multithreading.

Multiprocessing increases computing power by using two or more CPUs, whereas multithreading increases computing power using a single process with several code segments. 
Multiprocessing focuses on producing computer threads from a single process, whereas multithreading improves computing capability by adding CPUs.
 

Can a single server have multiple client connections?

A server can open WebSocket connections with numerous clients, including multiple connections from the same client. It can then send messages to one, all, or none of these people.
 

Differentiate between a port and a socket.

A port is a logical construct allocated to network processes to identify them within the system. A socket is made up of a port and an IP address.
A port number is assigned to an incoming packet and is used to identify the process that will consume it.
 

How many types of sockets are available to design?

There are two sorts of sockets: connection-oriented and connectionless.

Conclusion

This article extensively discussed socket programming with multithreading in Python. We learned to create a socket and connect to a server using threads. In the end, we have covered the client-server program. 

Recommended Readings:

We hope that this blog has helped you enhance your knowledge regarding socket programming with multithreading in Python. If you would like to learn more, check out our articles on Python or its application at Code studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass