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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With