You are currently viewing Build WebSocket Server and Client Using Python

Build WebSocket Server and Client Using Python

You must have seen real-time applications where data is changed frequently or updated in real-time, this happens because that application is using a WebSocket to achieve this functionality.

By the end of this article, you’ll able to learn:

  • What is WebSocket?
  • How to create a WebSocket server and client using Python?

What is WebSocket?

A WebSocket allows two-way communication (bidirectional) between two entities over a single TCP connection. This means a WebSocket client and server can interact with each other multiple times in a single connection.

A Websocket connection is a fully-duplex connection protocol which means the data can be sent and received simultaneously in both directions, keeping the connection alive until either server or client decides to stop the connection.

It is used in real-time applications to exchange low-latency data in both directions.

How to Create a WebSocket using Python

In this section, you will create a WebSocket server and client using Python. You will use Python’s websockets library to create a server and a client.

Install Dependency

Open your terminal window and run the following command:

Using the websockets library, you can create a websocket server and client in Python super easily.

Create a WebSocket Server

In this section, you’ll create a WebSocket server that will retrieve the values from the client and based on those values sends the appropriate response to the client.

The above code imports the websockets library for creating a WebSocket server and communicating with it and the asyncio library for making use of asynchronous tasks.

The code then defines an asynchronous function called ws_server() that takes WebSocket connection (websocket) as its parameter.

Inside the function, a try block is used that handles the incoming messages from the client. Within the try block, a while loop is created which means the code will run continuously.

Within the loop, the code receives two values from the client using the websocket.recv() and stores them within the name and age variables respectively. The code checks if any of the value is missing, if it is then it prompts a message and breaks the loops otherwise it proceeds and prints the values received from the client.

The code then sends the appropriate response back to the client based on the values it gets.

In the except block, the code handles any websockets.ConnectionClosedError exceptions that indicate an error occurred during the connection.

The code then defines another asynchronous function called main() that starts a WebSocket server. The WebSocket server is created using websockets.serve() method which listens on localhost and port 7890.

The server will run forever due to asyncio.Future(). This will keep the server alive and run continuously to listen to incoming messages.

In the end, the main() function is run using the asyncio.run(main()).

Create a WebSocket Client

In this section, you’ll create a client that takes the input from the user and displays the response sent by the WebSocket server.

The above code defines an asynchronous function called ws_client(). Inside the function, the WebSocket client is connected to the WebSocket server using the websockets.connect() method passed with the URL (ws://127.0.0.1:789) of the server created in the previous section.

The user is prompted to enter the name and if they type “exit”, the code quits the process. Then the user is asked to enter their age and both values (name and age) are sent to the WebSocket server using the ws.send() method.

After that, the code enters the infinite loop to continuously listen to the incoming messages from the server using the ws.recv() method. The message is then printed on the console.

Finally, the ws_client() function is run using asyncio.run(ws_client()). This will start the WebSocket client to accept the information from the user and display the response sent by the server.

Running the WebSocket Server and Client

You need to put the server and client code in two separate Python files. First, you need to run the WebSocket server script to start the server.

Open a terminal window, navigate to the project directory, and run the script file, in this case, the script is stored in the main.py Python file.

Now open another terminal window and run the WebSocket client script, in this case, the script is stored in the client.py file.

This will start the WebSocket client connected to the server. You will see the prompts asking for your name and age.

WebSocket client

Here, "Sachin" and "22" are sent to the server, and in return, the server responds with the "Welcome aboard, Sachin" message on the console.

The information entered by the user will be displayed on the WebSocket server console. You can see this in the image below.

WebSocket server

You can also run the client using the websockets interactive shell using the following command.

Conclusion

In this article, you learned to create a WebSocket server and client using the websockets library in Python. This technology is used in applications in which data changes in real-time.

Resource: https://websockets.readthedocs.io/en/stable/howto/quickstart.html


πŸ†Other articles you might be interested in if you liked this one

βœ…Create multi-threaded Python programs using a threading module.

βœ…What is the StandardScaler function in Machine Learning?

βœ…Upload and display images on the frontend using Flask.

βœ…What is Python coroutines and how to use it to execute tasks asynchronously?

βœ…How to use async/await in Python using the asyncio module?

βœ…How to create a database on Appwrite cloud using only Python.


That’s all for now

Keep Coding✌✌