block by redblobgames 64a67f21ba4741e3e1b79d27d09fa076

Hello World of websockets, javascript client, python server

Full Screen

index.html

<html>
  <head>
    <title>Testing web sockets</title>
    <script type="module" src="client.js"></script>
  </head>
  <body>
    <h1>Testing web sockets</h1>
    Sent:
    <pre id="send"></pre>
    Received:
    <pre id="recv"></pre>
  </body>
</html>

client.js

/**
    * This is based on the example code from
    * https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
 */

const exampleSocket = new WebSocket("ws://localhost:9999");

function send(msg) {
    document.querySelector("#send").textContent += msg + "\n";
    exampleSocket.send(msg);
}

function recv(msg) {
    document.querySelector("#recv").textContent += msg + "\n";
}

exampleSocket.onopen = (event) => {
    send("Here's some text that the server is urgently awaiting!");
};

exampleSocket.onmessage = (event) => {
    recv(event.data.toString());
};

server.py

#!/usr/bin/env -S uv run --with=websockets

"""
This is the example from https://websockets.readthedocs.io/en/stable/
"""

from websockets.sync.server import serve


def echo(websocket):
    for message in websocket:
        reply = f"{len(message)} bytes received as {message!r}"
        websocket.send(reply)


def main():
    with serve(echo, "localhost", 9999) as server:
        server.serve_forever()


if __name__ == "__main__":
    main()