Overview Of Socketserver.threadingtcpserver

Overview:

  • To create a TCP network server that serve each its client connection in a separate thread the ThreadingTCPServer class can be used.

 

  • The capability of spawning separate threads for each connection is inherited through the ThreadinMixin, which is the base class for ThreadingTCPServer. However, as per the design of   socketserver framework ThreadingTCPServer and any other derived classes of it are the classes, which should be used for implementing TCP servers.

 

  • ThreadingTCPServer sub-classes can potentially implement thread pool schemes and any other fine-grained dynamism required in implementing a multithreaded TCP based network server.

Creating a multithreaded TCP Server:

  • A request handler class should be defined for the TCP Server.  To handle TCP requests the class StreamRequestHandler should be sub-classed and the handle() method should be overridden.

 

  • An instance of ThreadingTCPServer should be created, by providing a tuple containing the IP address and the Port number on which the TCP server will listen along with the name of the request handler.

Example – Multi-threaded TCP Server:

import socketserver

import threading

 

ServerAddress = ("127.0.0.1", 6060)

 

class MyTCPClientHandler(socketserver.StreamRequestHandler):

    def handle(self):

        # Receive and print the data received from client

        print("Recieved one request from {}".format(self.client_address[0]))

        msg = self.rfile.readline().strip()

        print("Data Recieved from client is:".format(msg))

        print(msg)  

        print("Thread Name:{}".format(threading.current_thread().name))

 

# Create a Server Instance

TCPServerInstance = socketserver.ThreadingTCPServer(ServerAddress, MyTCPClientHandler)

 

# Make the server wait forever serving connections

TCPServerInstance.serve_forever()

 

Example – Multi-threaded TCP Client:

#import the socket module

import socket

 

#import the threading module

import threading

 

def Connect2Server():

    #Create a socket instance

    socketObject = socket.socket()

 

    #Using the socket connect to a server...in this case localhost

    socketObject.connect(("localhost", 6060))

    print("Connected to localhost")

 

    # Send a message to the web server to supply a page as given by Host param of GET request

    HTTPMessage = "GET / HTTP/1.1\r\nHost: localhost\r\n Connection: close\r\n\r\n"

    bytes       = str.encode(HTTPMessage)

 

    socketObject.sendall(bytes)

 

    # Receive the data

    while(True):

        data = socketObject.recv(1024)

        print(data)

 

        if(data==b''):

            print("Connection closed")

            break

 

    socketObject.close()

 

 

print("Client - Main thread started")  

ThreadList  = []

ThreadCount = 20

 

 

for index in range(ThreadCount):

    ThreadInstance = threading.Thread(target=Connect2Server())

    ThreadList.append(ThreadInstance)

    ThreadInstance.start()

 

# Main thread to wait till all connection threads are complete

for index in range(ThreadCount):

    ThreadList[index].join()

 

 

 

Output-Multi-threaded TCP Server:

Recieved one request from 127.0.0.1

Data Recieved from client is:

b'GET / HTTP/1.1'

Thread Name:Thread-1

.

.

.

Recieved one request from 127.0.0.1

Data Recieved from client is:

b'GET / HTTP/1.1'

Thread Name:Thread-20

Output-Multi-threaded TCP Client:

Connected to localhost

b''

Connection closed

.

.

.

Connected to localhost

b''

Connection closed

 


Copyright 2023 © pythontic.com