Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websockets not working in javascript and python

I am wrote a basic Websocket client-server code while learning it. The server program is in Python and Client program is in Javascript. The server side is sending messages but client isn't receiving. Can you guys tell what's wrong?

Javascript Code:

<script type="text/javascript">
    let socket = new WebSocket("ws://localhost:8765");

    socket.onconnect = function(event){
        console.log('Connected.');
    }

    socket.onmesssage = function(event)
    {
        console.log("Message received, " + event.data);
        var a = document.getElementById("p1");
        a.innerHTML = "You are client no.:" + event.data;
    }
</script>

Python Code:

import asyncio, websockets
i=0

async def start(websocket, path):
    global i
    i += 1
    await websocket.send(str(i))
    print("Number of clients: " + str(i));

print('Started...')
start_server = websockets.serve(start, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

The Javascript code doesn't work at all but Python code works(it print's statements after sending message).

like image 292
6575 Avatar asked Dec 02 '25 00:12

6575


1 Answers

There is a typo by the way.

It should be socket.onmessage NOT onmesssage There are 3 s in your code. Change to..

socket.onmessage = function(event)
    {
        console.log("Message received, " + event.data);
        var a = document.getElementById("p1");
        a.innerHTML = "You are client no.:" + event.data;
    }
like image 127
Nithin Thampi Avatar answered Dec 04 '25 14:12

Nithin Thampi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!