Skip to content

Instantly share code, notes, and snippets.

@mrecachinas
Last active August 11, 2021 20:49
Show Gist options
  • Save mrecachinas/78c94fc1d565ea7e842e1a077d2a6afa to your computer and use it in GitHub Desktop.
Save mrecachinas/78c94fc1d565ea7e842e1a077d2a6afa to your computer and use it in GitHub Desktop.
Websocket Trickery

To run:

python3 -m pip install websockets
python3 simple_websocket_server.py

Then in another terminal, run

python3 -m http.server

Open a web browser and navigate to http://localhost:8000/index.html.

Note that after 10 seconds, we get rid of the reference to the websocket object (both via setting it to null as well as delete-ing the property). Despite this, the connection is unbroken and the messages keep coming.

<!DOCTYPE html>
<html lang="en">
<head>
<style>
#receivedTime, #receivedMsg {
display: inline-block;
}
</style>
</head>
<body>
<h1>Websocket Test</h1>
<div id="note"></div>
<div id="receivedTime"></div> | <div id="receivedMsg"></div>
<script>
const obj = {
ws: (() => {
const ws = new WebSocket('ws://localhost:8080/');
ws.onopen = () => {
console.log("Websocket opened");
};
ws.onmessage = (message) => {
console.log("Received: " + message.data);
document.getElementById("receivedTime").innerHTML = new Date().toISOString();
document.getElementById("receivedMsg").innerHTML = message.data;
};
ws.onclose = () => {
console.log("Websocket closed");
};
ws.onerror = () => {
console.log("Websocket error");
};
})()
};
setTimeout(() => {
console.log("Deleting obj.ws");
obj.ws = null;
delete obj.ws;
console.log("Deleted obj.ws");
document.getElementById("note").innerHTML = `Deleted obj.ws at ${new Date().toISOString()}`;
}, 10000);
</script>
</body>
</html>
#!/usr/bin/env python
import asyncio
import json
import time
import websockets
async def hello(websocket, path):
print(f"Someone connected! {path}")
while True:
msg = "Hello, world!"
await websocket.send(msg)
time.sleep(1)
if __name__ == "__main__":
start_server = websockets.serve(hello, "localhost", 8080)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment