How To Do Real-time Data Visualization with Python WebSocket and Frontend

In this article, we will explore how to create a real-time application using Python WebSockets and frontend. We will build a server using Python asyncio library and websockets module, which will handle incoming connections from clients and send messages to all connected clients.

What is WebSocket?

WebSocket is a protocol that provides full-duplex (bidirectional) communication between a client and a server over a single, long-standing connection.

It enables real-time data transfer and is frequently used in web applications like online games, chat programs, and real-time data visualization that call for real-time communication between the client and the server.

Prerequisites

Before we begin, make sure you have Python installed on your computer.

Step 1) WebSocket Connection with Python, Let’s start with the code

import asyncio
import websockets


class Main:
    def __init__(self):
        self.connected = set()

    async def server(self, websocket, path):
        # Register.
        self.connected.add(websocket)
        try:
            async for message in websocket:
                for conn in self.connected:
                    if conn == websocket:
                        await conn.send(f'Got a new MSG FOR YOU: {message}')
        finally:
            # Unregister.
            self.connected.remove(websocket)
        
x = Main()
start_server = websockets.serve(x.server, "localhost", 8080)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
  • The above code defines a class Main with an __init__  method that initializes an empty set called connected. This set will store all connected clients.
  • The server method is the core of the server, which will handle incoming connections from clients and broadcast the received message to all connected clients. The async for loop listens for incoming messages from a client and then sends the message to all connected clients using the send method.
  • When a new client connects to the server, the register method is called, which adds the WebSocket connection to the connected set.
  • When a client disconnects, the unregister method is called, which removes the WebSocket connection from the connected set.
  • Finally, we create an instance of the class and start the server on localhost at port 8080  using the websockets.serve method. The run_until_complete method runs the server until it completes, and the run_forever method keeps the server running indefinitely.
  • To test this server, we need to create a front-end client that will connect to this server and display the messages received from the server in real time.

Step 2)  Connect Frontend with WebSocket

  • First of all, create one HTML file. Our HTML file will contain a form with text input and a submit button for sending messages and a list element for displaying messages.
<!DOCTYPE html>
<html>

<head>
    <title>WebSocket Demo</title>
</head>

<body>
    <h1>WebSocket Demo</h1>
    <input type="text" id="message-input" placeholder="Enter a message">
    <button id="send-button">Send</button>
    <ul id="message-list"></ul>
    <script>
        var socket = new WebSocket("ws://localhost:8080");
        var messageList = document.getElementById("message-list");
        var messageInput = document.getElementById("message-input");
        var sendButton = document.getElementById("send-button");

        socket.onopen = function() {
            console.log("WebSocket opened");
        };

        socket.onmessage = function(event) {
            var message = document.createElement("li");
            message.textContent = event.data;
            messageList.appendChild(message);
        };

        socket.onclose = function() {
            console.log("WebSocket closed");
        };

        sendButton.addEventListener("click", function() {
            var message = messageInput.value;
            socket.send(message);
            messageInput.value = "";
        });
    </script>
</body>

</html>
  • we will create a WebSocket object and add event listeners for onopen, onmessage, and onclose events.
  • When the WebSocket connection is opened, we will log a message to the console. When a message is received, we will create a new li element with the message text and append it to the ul element.
  • Finally, when the connection is closed, we will log another message to the console.

I hope this article helps you and you will like it.

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Submit a Comment

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

Subscribe

Select Categories