Skip to content

Instantly share code, notes, and snippets.

@akiross
Created March 16, 2019 18:35
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save akiross/a423c4e8449645f2076c44a54488e973 to your computer and use it in GitHub Desktop.
Save akiross/a423c4e8449645f2076c44a54488e973 to your computer and use it in GitHub Desktop.
A simple example of using websockets with starlette.io (it's super easy, wow!)
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.websockets import WebSocket
from jinja2 import Template
import uvicorn
template = """\
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function runWebsockets() {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onopen = function() {
console.log("Sending websocket data");
ws.send("Hello From Client");
};
ws.onmessage = function(e) {
alert(e.data);
};
ws.onclose = function() {
console.log("Closing websocket connection");
};
} else {
alert("WS not supported, sorry!");
}
}
</script>
</head>
<body><a href="javascript:runWebsockets()">Say Hello From Client</a></body>
</html>
"""
app = Starlette()
@app.route('/')
async def homepage(request):
return HTMLResponse(Template(template).render())
@app.websocket_route('/ws')
async def websocket_endpoint(websocket):
await websocket.accept()
# Process incoming messages
while True:
mesg = await websocket.receive_text()
await websocket.send_text(mesg.replace("Client", "Server"))
await websocket.close()
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment