Search code examples
javascriptpythonwebsocket

Python websocket send data to js + html


This is what I wanna do: websocket client --> websocket server --> websocket client javascript +html

I know how to send data from client to server but how can I print the output on html ??

html file :

const ws = new WebSocket("ws://localhost:8001/");
?
?

UPDATE

so I add this in js file

function initWebSocket() {
    console.log('Trying to open a WebSocket connection…');
    websocket = new WebSocket(gateway);
    websocket.onopen = onOpen;
    websocket.onclose = onClose;
    websocket.onmessage = onMessage;
}
websocket.onmessage = function(event)  {
    console.log(event.data);
    document.getElementById('test').innerHTML = event.data;
} 

and in my html file

<p class="reading"><span id="test"></span> &deg;C</p>

still not showing the update when I send some input with:

python -m websockets ws://localhost:8001/

UPDATE2 I want the js client to listen to websocket server output , onmessage won't work like this but how to do this ?


Solution

  • Don't work wih websocket for the way I described it , works with socket.io