How to use Flask-Sockets? Getting a KeyError: 'wsgi.websocket' How to use Flask-Sockets? Getting a KeyError: 'wsgi.websocket' flask flask

How to use Flask-Sockets? Getting a KeyError: 'wsgi.websocket'


Ah, thats the problem, you cant just visit the websocket endpoint with regular GET request, that way the wsgi.websocket will not be set to environ.

Also use gunicorn not the dev server, it comes with preconfigured worker:

# install from pippip install gunicorn# run app located in test.py module (in test.py directory)gunicorn -k flask_sockets.worker test:app

I made quick example here, be sure to update the address and port to match your setup.

<!DOCTYPE html><html>  <head>    <script type="text/javascript">       var ws = new WebSocket("ws://localhost:8000/echo");       ws.onopen = function() {           ws.send("socket open");       };       ws.onclose = function(evt) {           alert("socket closed");       };    </script>  </head></html>

That way the browser sends a request to the server, indicating that it wants to switch protocols from HTTP to WebSocket.

Feel free to read some more about websockets here:


It seems that Flask-Sockets does not provided a socket server so you either have to set up nginx to proxy web sockets, run your app using gunicorn or create a socket server yourself.

I found this helpful https://gist.github.com/lrvick/1185629


If using AWS, I found that sometimes need to edit the security group so that port 80 (and 443) are of type 'Custom TCP Rule' and not HTTP (and HTTPS)