Explain Python Socket Programming – Server, Client Example

Explain Python Socket Programming – Server, Client Example

This article will make Python socket programming super easy to understand. A socket is a quick connection that lets different computer programs talk to each other on the same computer or over a network. It’s commonly used for web browsing, file sharing, and messaging apps like WhatsApp.

In a socket setup, you have two main parts: the client (requester) and the server (listener). The client asks for something, and the server gives it back.

Making a client and server is easy in Python because Python has built-in tools for this kind of communication. Many popular programs we use daily, like web browsers and messaging apps, rely on sockets.

Socket Example:

We mentioned before that a socket client asks the socket server for resources, and the server replies to that request. Now, let’s design both the server and the client models so they can talk to each other. Here are the steps we’ll follow:

  1. The Python socket server program kicks off and patiently waits for any requests.
  2. The Python socket client program takes the lead in starting the conversation.
  3. The server program then responds accordingly to the requests made by the client.
  4. If the user enters a “bye” message, the client program wraps up and terminates.

Optionally, the server program can terminate when the client program ends. Alternatively, the server can continue running indefinitely or stop based on a specific command in the client’s request.

Python Socket Server

We’ll save our Python socket server program as socket_server.py. To enable Python socket connections, we start by importing the socket module. Next, we perform a series of tasks to establish a connection between the server and the client. We can obtain the host address using the socket.gethostname() function. Using a port address above 1024 is advisable because port numbers below 1024 are reserved for standard internet protocols. Look at the example code for a Python socket server below; the comments will guide you through understanding the code.

Example:

First, create the “ServerDemo.py” file

import socket
def custom_server():
    # get the server's hostname
    server_host = socket.gethostname()
    server_port = 5001  # choose a port number above 1024
    server_socket = socket.socket()  # create a socket instance
    server_socket.bind((server_host, server_port))  # bind host address and port together
    # configure how many clients the server can listen to simultaneously
    server_socket.listen(2)
    connection, client_address = server_socket.accept()  # accept a new connection
    print("Connection from: " + str(client_address)
    while True:
        # receive data stream; won't accept data packets greater than 1024 bytes
        data = connection.recv(1024).decode()
        if not data:
            # if no data is received, break out of the loop
            break
        print("From connected user: " + str(data))
        data = input(' -> ')
        connection.send(data.encode())  # send data to the client
    connection.close()  # close the connection
if __name__ == '__main__':
    custom_server()

Save $100 in the next
5:00 minutes?

Register Here

Output:

python3 ServerDemo.py

So, our Python socket server is running on port 5001 and is waiting for client requests. If you want the server not to quit when the client connection is closed, you can remove the if condition and break statement. The while loop in Python runs the server program indefinitely, continuously waiting for client requests. The server will persistently listen for and respond to incoming connections.

Python Socket Client

We’ll save our Python socket client program as socket_client.py. This program is quite similar to the server program, with the main difference being the absence of binding. Unlike the server program, the client doesn’t need to bind the host and port addresses together. Look at the Python socket client example code below; the comments will guide you through understanding the code.

Example:

First, create the “SocketDemo.py” file

import socket
def custom_client():
    custom_host = socket.gethostname()  # as both code is running on the same PC
    custom_port = 5001  # socket server port number
    custom_socket = socket.socket()  # instantiate
    custom_socket.connect((custom_host, custom_port))  # connect to the server
    custom_message = input(" -> ")  # take input
    while custom_message.lower().strip() != 'bye':
        custom_socket.send(custom_message.encode())  # send message
        custom_data = custom_socket.recv(1024).decode()  # receive response
        print('Received from server: ' + custom_data)  # show in terminal
        custom_message = input(" -> ")  # again take input
    custom_socket.close()  # close the connection
if __name__ == '__main__':
    custom_client()

Output:

python3 SocketDemo.py

To check the results, start by running the socket server program. Next, run the socket client program. Once both run, type a message in the client program and observe the output.

in the below Screenshot, the user says “hello” to the server

Now the server says “yes” to the user

Please note that the socket server is operating on port 5001. However, the client also needs a port to connect with the server. This port is assigned automatically by the client connect call, and in this instance, it is set to 53420.

Save $100 in the next
5:00 minutes?

Register Here

Conclusion:

In this article, we learned that a socket is a crucial part of computer networking. We also figured out how to create a simple program in Python for both the client and server sides using the socket module. It’s like using a tool to make computers talk to each other!