Multithread Socket Programming in Python

Python Methods and Functions

Socket Programming - & gt; This helps us connect the client to the server. Client — the sender and recipient of the message, and the server — just a listener that works on the data sent by the client.

What is a theme?
Stream — it is a lightweight process that does not require a lot of memory and is less expensive than processes.

What is multithreaded socket programming?
Multithreading — it is the process of concurrent execution of multiple threads in one process.

Multithreaded modules:
_Thread module & amp; threading module used for multithreading in python, these modules help in synchronization and ensure that the thread is being used.

 from _thread import * import threading 

The lock object is created- & gt;

 print_lock = threading.Lock () 

A lock has two states: "locked" or "unlocked". It has two main methods acqu () and release (). When the state is unlocked, print_lock.acquire () is used to change the state to locked, and print_lock.release () is used to change the state to unlock.

Function thread.start_new_thread () is used to start a new thread and return its ID. The first argument — this is the called function, and the second — a tuple containing a positional list of arguments.

Let's learn programming client-server multithreaded sockets with
Note: -The code works with python3.

Multithreaded server-side code

# import socket programming library

import socket

  
# import thread module

from _ thread import *

import threading

 

print_lock = threading.Lock ()

  
# stream function

def threaded (c):

while True :

 

# data received from the client

data = c.recv ( 1024 )

if not data:

print ( 'Bye' )

  

  # unlocked on exit

print_lock.release ()

break

 

  # discard the given string from the client

data = data [:: - 1 ]

 

# send back string back to client

c.send (data)

 

  # closed

c.close ()

 

  

def Main ():

host = ""

 

# change the port on your computer

# in our case it is 12345 but this is

# 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 socket in listening mode

s.listen ( 5 )

print ( "socket is listening" )

  # forever loop until the client wants to exit

  while True :

 

# contact customer

c, addr = s.accept ()

 

# the lock received by the client

  print_lock.acquire ()

print ( 'Connected to:' , addr [ 0 ], ':' , addr [ 1 ])

 

# Start a new stream and return its ID

start_new_thread (threaded, (c,))

  s.close ()

 

  

if __ name__ = = '__main__' :

Main ()

 Console Window: socket binded to port 123 45 socket is listening Connected to: 127.0.0.1: 11600 Bye 

Client Code

# Import the module socket

import socket

  

  

def Main ():

# local host IP & # 39; 127.0.0.1 & # 39;

host = ' 127.0.0.1'

 

# Determine the port you want to connect to

  port = 12345

  

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

 

# connect to the server on the local computer

s.connect ((host, port))

 

# the message you are sending to the server

message = "shaurya says pythonengineering"

while True :

 

# message sent to server

  s.send (message.encode ( 'ascii' ))

 

# message received from server

data = s.recv ( 1024 )

 

# print the received message

# postback will be here

 

print ( 'Received from the server:' , str (data.decode ( 'ascii' )))

  

# ask client if he wants to continue

ans = input ( 'Do you want to continue (y / n):' )

if ans = = 'y' :

  continue

else :

  break

# close 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 & gt; 
https://docs.python.org/2/library/thread.html

This article courtesy of SHAURYA UPPAL . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials