How To Create Client & Server Socket In Python With Example

This article will tell you how to develop a client-server socket application using the Python socket module with examples. It will create both TCP and UDP protocol socket client and server.

1. How To Create TCP Client / Server Socket App In Python.

1.1 Create TCP Client Socket In Python Steps.

  1. Import the python socket module, this is a built-in module.
    import socket
  2. Call the socket.socket(socket.AF_INET, socket.SOCK_STREAM) function to create the client socket, please note the function parameters.
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3. Connect to the server socket by invoking the above client socket object’s client_socket.connect((‘localhost’, 8999)) function. The connect() function’s input parameter is a tuple object that contains the server socket machine hostname/IP and port number.
    client_socket.connect(('localhost', 8999))
  4. Call the client socket object’s send() or sendall() function to send text data to the server socket. The function’s input parameter is a bytes object, so you need to encode the send text before sending it.
    client_socket.sendall(user_input_str.encode('utf-8'))
  5. Call the client socket object’s client_socket.recv(1024) function to read the text that the server socket sends back.
    data_tmp = client_socket.recv(1024)
  6. The received data is also a bytes object, you need to convert it to a text string by invoking the bytes object’s function decode(‘utf-8’).
    str_tmp = data_tmp.decode('utf-8')
  7. Call the client socket’s close() function to close the socket connection.
    client_socket.close()

1.2 Create TCP Server Socket In Python Steps.

  1. Import the python socket module.
    import socket
  2. Create the server socket object by invoking the function socket.socket(socket.AF_INET, socket.SOCK_STREAM).
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3. Bind the socket object to a host and a port number with the socket object’s bind( server_info_tuple_object ) function.
    server_socket.bind(('localhost', 8080))
    
  4. Make the socket object be a server socket by invoking it’s listen(maximize_queue_size) function. The maximize_queue_size parameter is the number of the maximize socket connections that are waiting for the server socket to accept in the queue.
    server_socket.listen(1)
  5. Call the server socket object’s accept() function to accept the client socket request, it will return a connection object and the client socket IP address.
    (connection, client_ip) = server_socket.accept()
  6. Call the connection object’s recv(buffer_size) function to read the data sends from the client socket.
    data = connection.recv(1024)
  7. The readout data is also a bytes type object, you need to invoke it’s decode(‘utf-8’) function to convert it to a string.
    data_str = data.decode('utf-8')
  8. Call the connection object’s send(data) or sendall(data) function to send data back to the client socket.
    connection.sendall('hello client, just received your data.'.encode('utf-8'))
  9. Call the connection object’s close() function to close the socket connection.
    connection.close()

2. How To Create UDP Client / Server Socket App In Python.

2.1 Create UDP Client Socket In Python Steps.

  1. Import the python socket module, this is a built-in module.
    import socket
  2. Call the socket.socket(socket.AF_INET, socket.SOCK_DGRAM) function to create the UDP client socket, please note the function parameters.
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  3. Call the UDP client socket object’s sendto(data, udp_server_socket_info_tuple) function to send data to the UDP server socket.
    client_socket.sendto(user_input_str.encode('utf-8'), udp_server_tuple)
  4. The udp_server_info_tuple variable’s value is something like (‘127.0.0.1’, 8999) that contains the UDP server IP and port number.
  5. Call the UDP client socket object’s close() function to close the socket connection.
    client_socket.close()

2.2 Create UDP Server Socket In Python Steps.

  1. Import the python socket module.
    import socket
  2. Create the server socket object by invoking the function socket.socket(socket.AF_INET, socket.SOCK_STREAM).
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3. Bind the socket object to a host and a port number with the socket object’s bind( server_info_tuple_object ) function.
    server_socket.bind(('localhost', 8080))
  4. Call the server socket object’s recvfrom(buffer_size) function to receive the data sent from the client.
    data, client_ip = server_socket.recvfrom(1024)
  5. The function recvfrom(buffer_size) returns the received data and the client IP address, the returned data is a bytes type object, you need to decode it to string using it’s decode(‘utf-8’) function.
    data.decode('utf-8')

3. Create Client-Server TCP / UDP Socket Example.

  1. The above video is the example demo video.
  2. There are 2 python source files TCPSocketExample.py and UDPSocketExample.py in this example. The first file will demo the TCP socket, the second file will demo the UDP socket.
    TCPSocketExample.py
    UDPSocketExample.py
  3. When you run this example in the command line console, it will prompt you to type character s or c. Type s means to create a server socket, type c means to create a client socket.
    > python .\TCPSocketExample.py
    Input s to create server socket, input c to create client socket:
    
    > python .\UDPSocketExample.py
    Input s to create server socket, input c to create client socket:
    
  4. When you type s, you can get the below output on the console.
    > python .\TCPSocketExample.py
    Input s to create server socket, input c to create client socket:
    s
    TCP server socket started and bind to host : localhost, port_number : 8999
    
    > python .\UDPSocketExample.py
    Input s to create server socket, input c to create client socket:
    s
    UDP server socket started and bind to host : localhost, port_number : 8999
  5. When you input character c, then you can input the data that you want to send to the server socket.
    > python .\TCPSocketExample.py
    Input s to create server socket, input c to create client socket:
    c
    Please input the text you want to sent to the TCP socket server:
    
    hello
    end
    <class 'socket.socket'>
    Data from server socket : hello client, just received your data.
  6. When you type & send the string ‘end‘ to the server socket, the server socket receives it and will close the socket connection.
  7. When the number of the client socket request is more than the maximum queue size you specified use the server_socket.listen(2) function ( for example start multiple client socket ), then the other client socket connects request will be rejected, you can see the below ConnectionRefusedError message.
    t> python .\TCPSocketExample.py
    Input s to create server socket, input c to create client socket:
    c
    Traceback (most recent call last):
      File ".\TCPSocketExample.py", line 106, in <module>
        client_socket.connect(('localhost', 8999))
    ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it.
  8. TCPSocketExample.py.
    import socket
    import time
    
    # This function will create a TCP client socket.
    def create_tcp_client_socket():
    
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        return client_socket
    
    # This function will create a TCP server socket that is bind on the bind_host and listen on the server_port_number port.
    def create_tcp_server_socket(bind_host, server_port_number):
    
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
        server_socket.bind((bind_host, server_port_number))
    
        # set the server socket queue maximize connection size. 
        # in the below configuration, if there are 2 socket connections in the queue are waiting for connecting, the server socket will reject other connections.  
        server_socket.listen(2)
    
        print('TCP server socket started and bind to host : ' + bind_host + ', port_number : ' + str(server_port_number))
    
        # initialize the connection variable to None.
        connection = None
    
        while True:
    
            if(connection == None):
                # accept the client connection and return the connection object and client ip.
                (connection, client_ip) = server_socket.accept()
    
            # get current time.
            current_time = time.localtime(time.time())
            #print(current_time)
    
            current_time_str = str(current_time.tm_hour) + ':' + str(current_time.tm_min) + ':' + str(current_time.tm_sec)
            #print(current_time_str)
    
            #print(current_time_str + ' - The client socket address is ' + client_ip[0])
    
            # receive the client socket sends text.
            data = connection.recv(1024)
            #print(type(connection))
            #data = recv_data_by_socket_connection(connection, 1024)
            print(current_time_str + ' - receive data : ' + data.decode('utf-8') + ', from ip :' + client_ip[0])
            
            # if client sends the string 'end', then close the current connection. 
            if data.decode('utf-8') == 'end':
                # send text back to the client.
                connection.sendall('hello client, just received your data.'.encode('utf-8'))
                # close the socket connection.
                connection.close()
                # set the connection object to NULL.
                connection = None
    
    
    def recv_data_by_socket_connection(socket_conn, buffer_size):
    
        # receive text data from the socket server.
        recv_data_str = ''
    
        try:
    
            print(type(socket_conn))
    
            data_tmp = socket_conn.recv(buffer_size)
    
            while True:
    
                str_tmp = data_tmp.decode('utf-8')
    
                if(len(str_tmp) ==0 ):
    
                    break
    
                recv_data_str = recv_data_str + str_tmp
    
                data_tmp = socket_conn.recv(buffer_size)
    
        except Exception as e: 
        
                print('Exception - ('+str(e)+') ')
    
        finally:
            
            return recv_data_str     
    
    
    if __name__ == '__main__':
    
        # get user input from the command line.
        user_input_str = input("Input s to create server socket, input c to create client socket:\r\n")
    
        # if user input string 's'.
        if(user_input_str=='s'):
            # create the TCP server socket.
            create_tcp_server_socket('localhost', 8999)
        # if user input string 'c'.
        if(user_input_str=='c'):
            
            # create the client socket object.
            client_socket = create_tcp_client_socket()
    
            # connect to the server socket with provided host and port number.
            client_socket.connect(('localhost', 8999))
    
            print("Please input the text you want to sent to the TCP socket server:\r\n")
    
            while True:
                # get user input string.
                user_input_str = input("")
                
                # send the user input to the server socket.
                client_socket.send(user_input_str.encode('utf-8'))
                client_socket.sendall(''.encode('utf-8'))
                
    
                # If user input the text 'end' then break the loop.
                if('end' == user_input_str):
    
                    break
                
            # receive text data from the socket server.
            recv_data_str = recv_data_by_socket_connection(client_socket, 1024)
            '''recv_data_str = ''
            data_tmp = client_socket.recv(10)
    
            while True:
                if not data_tmp:
                    break
    
                str_tmp = data_tmp.decode('utf-8')
                recv_data_str = recv_data_str + str_tmp
    
                data_tmp = client_socket.recv(10)'''
                
            # print out server returned data on client screen.
            print('Data from server socket : ' + recv_data_str)
            # close the connection.
            client_socket.close()
  9. UDPSocketExample.py

    import socket
    import time
    
    # create and return a UDP client socket object.
    def create_udp_client_socket():
    
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
        return client_socket
    
    # create the UDP server socket and listen for clinet to connect.
    def create_udp_server_socket(bind_host, server_port_number):
        
        # create the server side socket. 
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        
        # bind the server socket ip and listening port number. 
        server_socket.bind((bind_host, server_port_number))
    
        print('UDP server socket started and bind to host : ' + bind_host + ', port_number : ' + str(server_port_number))
    
        # the main loop.
        while True:
           
            # receive data from the client socket.
            data, client_ip = server_socket.recvfrom(1024)
    
            current_time = time.localtime(time.time())
            #print(current_time)
    
            current_time_str = str(current_time.tm_hour) + ':' + str(current_time.tm_min) + ':' + str(current_time.tm_sec)
            #print(current_time_str)
            
            # print the client send text on the screen.
            print(current_time_str + ' - receive data : ' + data.decode('utf-8') + ', from ip :' + client_ip[0])
            
    
    
    if __name__ == '__main__':
    
        # get user input text.
        user_input_str = input("Input s to create server socket, input c to create client socket:\r\n")
    
        # if user input 's'.
        if(user_input_str=='s'):
            
            # create the UDP server socket.
            create_udp_server_socket('localhost', 8999)
        
        # if user input 'c'.
        if(user_input_str=='c'):
    
            # create the UDP client socket.
            client_socket = create_udp_client_socket()
    
            print("Please input the text you want to sent to the UDP socket server:\r\n")
    
            while True:
    
                # get user input.
                user_input_str = input("")
                 
                # create a tuple object that contains the UDP server ip and port number. 
                udp_server_tuple = ('127.0.0.1', 8999)
    
                # send data to the UDP server socket.
                client_socket.sendto(user_input_str.encode('utf-8'), udp_server_tuple)
    
                # if user input 'end' then exit the loop.
                if('end' == user_input_str):
    
                    break
                
            # close the socket connection.    
            client_socket.close()

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.

Clicky