How To Use Python SocketServer Module With Example

Besides the python socket module, you can also use the python socketserver module to create TCP & UDP servers. The socketserver python module is easier to use than the socket module. This article will tell you how to use it with examples.

1. Create TCP & UDP Server Using Python socketserver Module Steps.

1.1 Create TCP or UDP Request Handler Class.

  1. Create a python class that extends the socketserver.StreamRequestHandler class to implement the TCP socket handler object.
  2. Create a python class that extends the socketserver.DatagramRequestHandler class to implement the UDP socket handler object.
  3. Then you can override the setup(), handle(), and finish() method in your customize handler class. The handle() method is the method that will process the TCP or UDP socket request.
    class TCPRequestHandler(StreamRequestHandler):
    
        def setup(self) -> None:
            
            return super().setup()
    
        
        def handle(self) -> None:
    
            print('handle tcp socket request.')
    
    
        def finish(self) -> None:
    
            return super().finish()
    
    
    
    class UDPRequestHandler(DatagramRequestHandler):
    
        def setup(self) -> None:
    
            return super().setup()
    
        
        def handle(self) -> None:
    
            print('handle udp socket request.')
    
    
        def finish(self) -> None:
    
            return super().finish()

1.2 Create TCP or UDP Socket Server.

1.2.1 Create TCP Socket Server.
  1. Create an instance of the class socketserver.TCPServer or socketserver.ThreadingTCPServer with the provided server hostname or IP and port number, and the above customize TCPRequestHandler class.
    tcp_server = TCPServer((server_host, server_port_number), TCPRequestHandler)
  2. Then call the tcp_server object’s serve_forever() method to start the TCP server. Now when a TCP socket request comes in, the request will be processed by the custom TCPRequestHandler class’s handle() method.
    tcp_server.serve_forever()
1.2.2 Create UDP Socket Server.
  1. Create an instance of the class socketserver.UDPServer  or socketserver.ThreadingUDPServer with the provided server hostname or IP and port number, and the above customize TCPRequestHandler class.
    udp_server = UDPServer((server_host, server_port_number), UDPRequestHandler)
  2. Then call the udp_server object’s serve_forever() method to start the UDP server. Now when a UDP socket request package comes in, the request will be processed by the custom UDPRequestHandler class’s handle() method.
    udp_server.serve_forever()

2. Use Python serversocket Module To Create TCP & UDP Socket Server Example.

  1. You can see the example demo video at the end of this article.
  2. The example python source file name is SocketServerModuleExample.py.
  3. When you run it with the command python .\SocketServerModuleExample.py, it will let you create a TCP server ( tcp_s ),  a TCP client ( tcp_c ), a UDP server ( udp_s ), or a UDP client (udp_c).
    > python .\SocketServerModuleExample.py
    Input tcp_s to create TCP server socket, input tcp_c to create TCP client socket,
    Input udp_s to create UDP server socket, input udp_c to create UDP client socket:
    udp_s
    UDP server is started on host 'localhost:9999'
    
    Setup UDP request handler.
    Thu May  5 18:28:43 2022 - 127.0.0.1 - hello
    Finish UDP request handler.
    
    Setup UDP request handler.
    Thu May  5 18:28:47 2022 - 127.0.0.1 - how are you
    Finish UDP request handler.
  4. If you type udp_c then it will create a UDP client socket, and then you can input text to send to the UDP server, and you can see the console output on both the client-side and server-side.
    > python .\SocketServerModuleExample.py
    Input tcp_s to create TCP server socket, input tcp_c to create TCP client socket,
    Input udp_s to create UDP server socket, input udp_c to create UDP client socket:
    udp_c
    Input the data send to server:
    >hello
    >how are you
    >bye
  5. For the TCP socket server, it will read the client send data using the handler’s rfile.readline() method, it will write the data back to the client using the handler’s wfile.write(bytes_data) method.
  6. For the UDP socket server, it will get the client socket sent data using the handler’s request[0] attribute.
  7. Below is the SocketServerModuleExample.py file source code, you can read the source code to learn more.
    # https://blog.csdn.net/weixin_39716043/article/details/110982437
    # https://blog.csdn.net/SmartShepi/article/details/115405966
    
    #Python 3
    import socketserver
    
    #Python 2
    #import SocketServer
    
    from socketserver import StreamRequestHandler, DatagramRequestHandler
    from socketserver import ThreadingTCPServer, TCPServer, ThreadingUDPServer, UDPServer
    from time import ctime
    import socket
    
    class TCPRequestHandler(StreamRequestHandler):
    
        def setup(self) -> None:
    
            print('\nSetup TCP request handler.')
            
            return super().setup()
    
        
        def handle(self) -> None:
    
            client_ip = self.client_address[0]
    
            print("connected from " + client_ip)
    
            # The readline() function will return only when the client send a \n which is a new line character.
            # If the client do not send the \n character, then readline() mehtod will hang and never return.
            client_send_data_line = self.rfile.readline().strip()
    
            client_send_data_line_str = client_send_data_line.decode('utf-8')
    
            print('client_send_data_line : ' + client_send_data_line_str)
    
            curr_time = ctime()
    
            self.wfile.write((curr_time + ' - ' + client_send_data_line_str).encode('utf-8'))
    
    
        def finish(self) -> None:
    
            print('Finish TCP request handler.\r\n')
    
            return super().finish()    
    
    
    
    def create_tcp_server():
    
        server_host = 'localhost'
    
        server_port_number = 9999
    
        #tcp_server = ThreadingTCPServer((server_host, server_port_number), TCPRequestHandler)
        tcp_server = TCPServer((server_host, server_port_number), TCPRequestHandler)
    
        tcp_running_message = 'TCP server is started on host \'' + server_host + ':' + str(server_port_number) + '\'\r\n'
    
        print(tcp_running_message)
    
        tcp_server.serve_forever()
    
    
    
    def create_tcp_client():
    
        server_host = 'localhost'
    
        server_port_number = 9999
    
        buffer_size = 10
    
        print("Input the data send to server:")
    
        while True:
    
            tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
            tcp_client.connect((server_host, server_port_number))
    
            client_data = input(">")
    
            if client_data == 'bye':
    
                break
    
    
            # Add the '\r\n' character at the end of the sent data, because the TCP server handler will call the readline() function 
            # to get client send data, if the client does not send the '\n' character ( new line character ) then the server readline() 
            # function will hang and do not receive client send data.
            tcp_client.sendall((client_data + '\r\n').encode('utf-8'))
    
            server_data_all = ''
    
            server_data = tcp_client.recv(buffer_size).decode('utf-8').strip()
    
            while len(server_data) > 0:
    
                server_data_all += server_data
    
                server_data = tcp_client.recv(buffer_size).decode('utf-8').strip()
    
            print('server_data_all : ' + server_data_all)
            
        tcp_client.close()
    
    
    
    class UDPRequestHandler(DatagramRequestHandler):
    
        def setup(self) -> None:
    
            print('Setup UDP request handler.')
            
            return super().setup()
    
        
        def handle(self) -> None:
    
            client_address = self.client_address
    
            client_send_data = self.request[0].decode('utf-8').strip()
    
            curr_time = ctime()
    
            print(curr_time + ' - ' + client_address[0] + ' - ' + client_send_data)
    
            '''
            socket = self.request[1]
    
            socket.sendto(('UDP server return : ' + client_send_data).encode('utf-8'), client_address)
            '''
    
    
        def finish(self) -> None:
    
            print('Finish UDP request handler.\r\n')
    
            return super().finish()
    
    
    def create_udp_server():
    
        server_host = 'localhost'
    
        server_port_number = 9999
    
        #udp_server = ThreadingUDPServer((server_host, server_port_number), UDPRequestHandler)
        udp_server = UDPServer((server_host, server_port_number), UDPRequestHandler)
    
        udp_running_message = 'UDP server is started on host \'' + server_host + ':' + str(server_port_number) + '\'\r\n'
    
        print(udp_running_message)
    
        udp_server.serve_forever()
    
    
    
    def create_udp_client():
    
        server_host = 'localhost'
    
        server_port_number = 9999
    
        buffer_size = 10
    
        print("Input the data send to server:")
    
        while True:
    
            udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
            client_data = input(">")
    
            if client_data == 'bye':
    
                break
    
            udp_client.sendto((client_data + '\r\n').encode('utf-8'), (server_host, server_port_number))
    
        udp_client.close()    
    
    
    
    if __name__ == '__main__':
    
        user_input_str = input("Input tcp_s to create TCP server socket, input tcp_c to create TCP client socket, \r\nInput udp_s to create UDP server socket, input udp_c to create UDP client socket:\r\n")
    
        # if user input string 'tcp_s'.
        if(user_input_str=='tcp_s'):
            # create the TCP server socket.
            create_tcp_server()
    
        # if user input string 'tcp_c'.
        if(user_input_str=='tcp_c'):
            create_tcp_client()
    
        # if user input string 'udp_s'.
        if(user_input_str=='udp_s'):
            # create the UDP server socket.
            create_udp_server()
    
        # if user input string 'udp_c'.
        if(user_input_str=='udp_c'):
            create_udp_client()

3. Example Demo Video.

  1. You can see this example demo video from URL https://youtu.be/KpDsro7Zg1c.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.