Skip to content

Instantly share code, notes, and snippets.

@redblobgames
Created March 1, 2025 17:56
Show Gist options
  • Save redblobgames/64a67f21ba4741e3e1b79d27d09fa076 to your computer and use it in GitHub Desktop.
Save redblobgames/64a67f21ba4741e3e1b79d27d09fa076 to your computer and use it in GitHub Desktop.
Hello World of websockets, javascript client, python server
/**
* 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());
};
<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>
#!/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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment