简体   繁体   中英

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).

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM