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
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
"""
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()