Creating a Minimal WebSocket Connection in Python, Inspired by the Simplicity of Socket.IO

 Simple Websocket  Connection. LIke socket io.


main.py

import asyncio
import websockets
import uuid

connections = []

# when new socket connection comes this' function will executeed
async def handle_websocket(websocket, path): #<-- path of socket recived
    # creating uniq id
    connection_id = str(uuid.uuid4())
 
    # This function will be append new connection
    connections.append(connection_id)
   
   
    print("Connected:- ",connection_id)

    # < -- when user connected send him a message -- >
    await websocket.send(f"Your Id: {connection_id}")
   
    # < -- it\'s a user connection i'ts run antil user connected when user diconnected it will be ditoryed -- >
    try:
        while True:
            try:
                # Receive message from the client
                message = await websocket.recv()
               
                # Send a response back to the client
                response = f"Server received: {message}:"
                await websocket.send(response)
           
            # < -- user disconnected -- >
            except:
                await websocket.close()
                connections.remove(connection_id)
                print("Disconnected:- ",connection_id)
                break

    except Exception as error:
        print("error:- ",error)
       

# Create the WebSocket server
start_server = websockets.serve(handle_websocket, "localhost", 8765)

# Start the event loop
asyncio.get_event_loop().run_until_complete(start_server)

asyncio.get_event_loop().run_forever()


INDEX.HTML


<!-- Example HTML with JavaScript to connect to the WebSocket server -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Example</title>
</head>

<body>
    <input type="text" id="inputText">
    <button onclick="sendMsg()">send</button>
    <script>
        const socket = new WebSocket('ws://localhost:8765/connect');

        function sendMsg() {
            text = inputText.value
            socket.send(text);
        }
        document.addEventListener("keyup", (e) => e.key == "Enter" ? sendMsg() : null)
        // Connection opened
        socket.addEventListener('open', (event) => {
            console.log('WebSocket connection opened:', event);

            // Send a message to the server
            socket.send('Hello, WebSocket!');
        });

        // Listen for messages from the server
        socket.addEventListener('message', (event) => {
            console.log(event.data);
        });

        // Connection closed
        socket.addEventListener('close', (event) => {
            console.log('WebSocket connection closed:', event);
        });

        // Handle errors
        socket.addEventListener('error', (error) => {
            console.error('WebSocket error:', error);
        });

    </script>
</body>

</html>


Comments

Popular posts from this blog

Express Production Setup - 4 | HELMET

Express Production Setup - 3 | CORS

Ensuring File Creation in the Current Directory when Converting Python (.py) Script to Executable (.exe).