Created
March 1, 2025 17:56
-
-
Save redblobgames/64a67f21ba4741e3e1b79d27d09fa076 to your computer and use it in GitHub Desktop.
Hello World of websockets, javascript client, python server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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()); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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