Using WebSocket With Python

October 13, 2022
Websockets is a library for building



Overview

Python has gained a lot of traction over the past few years. It has become one of the most dynamic programming languages by the availability of a variety of libraries to work in almost every area of expertise. One such area is development and implementation of Internet transmission protocols. HTTP has been the very first and the most common choice for an application layer protocol but recently WebSocket protocol has become a good option for an application layer protocol.

python CTA

In this article, we will be discussing the features, life cycle and implementation of the WebSocket protocol using python.

WebSocket protocol

Before diving in with the implementation of WebSocket with python, firstly we need to understand what is WebSocket. In general, WebSocket is an application layer protocol like HTTP but it allows full-duplex bi-directional communication between a client and a server over a single TCP connection.

We have a python library, also called WebSocket that is used for building WebSocket servers and clients in Python. It is majorly known for its correctness, simplicity, robustness, and performance. It is built on top of asyncio, python’s standard asynchronous I/O framework and it provides a well-organized coroutine-based API.

HTTP Protocol

The HTTP protocol is the foundation of any data exchange on the Web. It is very similar to the WebSocket protocol as it also allows the fetching of resources and data over the internet. These resources include all types of data that we send or receive over the internet. The client can request the information with headers using actions like GET, POST or PUT and the server responds to the client accordingly. After this transaction, the connection is closed. For every communication like this, the HTTP protocol initiates a new connection, the data is then exchanged and then the connection is closed.

HTTP vs WebSocket

The HTTP has been working just fine but the issues started to arise when certain applications required to fetch the data continuously from the server. Such applications kept getting common day by day and it includes some very common applications such as online gaming applications, chat applications or real-time analytics and collaboration tools or cryptocurrency exchanges. It resulted in multiple HTTP calls being made to the server in very short intervals which is very difficult to handle.

Unlike HTTP, WebSocket uses a bi-directional communication channel that keeps the connection open until the client or server does not decide to close the connection. It also means that both the server and the client can push data at the same time after the connection is established connection. This solves the issue of the continuous need for data exchange and made it a very smooth process.

WebSocket implementation

Before we begin, it is to be noted that we will not be extensively focused on how WebSocket work. Instead, we will be discussing how to implement WebSocket in python to develop basic applications. It is assumed that you must be familiar with basic networking concepts like HTTP requests. Along with that, to implement WebSocket in python, you must have at least basic Python and JavaScript Programming knowledge.

Both the web browser and the server have to implement the WebSocket protocol to establish the connection and then for its maintenance. Once connected, the long-lived connection has various important implications for servers, unlike typical HTTP connections. It is to be noted that the WebSocket implementation is not designed to be used with servers that are based on multi-threads or multi-process architecture because they are not designed to scale appropriately for WebSocket. They are just designed to open a connection, handle a request as quickly as possible and then close the connection.

The web sockets are commonly used with asynchronous servers like Tornado or Green Unicorn monkey patched with “gevent” for any practical WebSocket server-side implementation. On the client side, it is not mandatory to use a JavaScript library for WebSocket, unlike HTTP implementation. The Web browser that will implement the WebSocket will itself expose all the necessary client-side functionality via the WebSocket object.

Although it is not mandatory, a JavaScript wrapper library is highly recommended to be used while implementing the web sockets. It is because it can provide a wrapper around a browser when WebSocket is not supported. It can make things very easier by implementing graceful degradation.

Tools for WebSocket Implementation

Following are some JavaScript client libraries and Python projects. These projects are used to either implement WebSocket in Python or provide an example code to follow to use WebSocket in your own projects.

Autobahn

First on the list is the autobahn subproject. It uses Twisted and asyncio to create the server-side WebSocket component with python while the AutobahnJS library assists on the client web browser side.

Django Channel

It is built on top of WebSocket and is very easy to be integrated with Django projects in python, regardless they are new or existing projects.

Flask-SocketIO

It is a Flask extension that is based upon the eventlet or gevent to create server-side WebSocket connections using python.

WebSocket-client

It also provides some low-level APIs for implementing WebSocket in python. It also works with both Python 2 and 3.

Crossbar.io

This python library is built upon Autobahn. If required by the web app developer, it can also provide a separate server for handling the WebSocket.

Implementing WebSocket using python

This process demonstrates the implementation of a simple WebSocket server, using the browser as the client to connect to the server. It is to be noted that this implementation does not aim to build a huge application but to give you a basic understanding of how to implement WebSocket with python and JavaScript to create WebSocket Applications.

Step 1: Setting up the environment

For the setup, you can use any of the projects mentioned above, but we will be using the WebSocket package.

Link: https://websockets.readthedocs.io/en/stable/index.html

You also need to install Python, preferably Python 3.6+. Once Python is installed on your system.

Use the following pip command to install the Web:

pip install websockets

after the installation, we can start creating the server and a client.

Step 2: Creating the Server

The process of creating a server start by first creating a directory and we are calling it WebSocket. Inside the directory, we have to create a python file and it will be named, server.py

Now, the following lines of code are needed to be added Inside the server.py file to implement a simple server on the / URL. inside the server file, we have to import the required packages, asyncIO and WebSocket.

Next, a handler will be created that takes the arguments WebSocket and path. The WebSocket represents the URL of the server (localhost:8000). The path is the URI for the handler, the URI is /.

Now we have to wait for the incoming connection and the message. When the data will be received an action will be implemented. In this demonstration, the action is a simple response to the contents of the received data.

You can see the code for all the mentioned stapes below:

import asyncio
import websockets
# creating a handler for each connection
async def handler(websocket, path):

    data = await websocket.recv()
    my_reply = f"Data received as:  {data}!"
    await websocket.send(my_reply)
start_server = websockets.serve(handler, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Step 3: Creating a client

Now, a simple client will be implemented to connect to the server. The Browser console is used as the client to keep this demonstration plain and simple.

First, an HTML file named, client.html will be created, it will contain the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
</head>

<body>
    <button onclick="contactServer">Click Here</button>
</body>


<script>
    const socket = new WebSocket('ws://localhost:8000');
socket.addEventListener('open', function (event) {
    socket.send('Connection Established');
});


socket.addEventListener('message', function (event) {
    console.log(event.data);
});
const contactServer = () => {
    socket.send("Initialize");
}
</script>
</html>

You have to save this file and open it using any browser. This will create the client. To test if the connection is working, click the only button shown on the top-left, “click here” and check the browser console for the server response.

As you click the button, a message will be sent to the server. The server then responds with the contents of the message, which will be indicating that the connection has been established. simple!

Wrapping it up

WebSocket is known for its robustness and performance and its implementation using Python opens up a lot of options for the functionalities of an application for developers. For this implementation, we have kept things to the bare minimum but you can implement the WebSockets connection using python for a variety of tasks. The different implementations of WebSockets using python offer the features for diverse applications including some very complex tasks.

Also Read: Top 6 Python Web Frameworks For Development

python CTA2



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US