Setup A Python Flask Web Server With WebSockets
### Overview
When you search `flask websockets` the first thing that comes up is Flask-SocketIO. Turns on, SocketIO and WebSockets aren't the same thing. Took me a while to figure that out. Once I did, I put together this example file of how to get flask and websockets running together via a single script. It:
- spins up a flask web server on port 5050 - spins up websockets on port 5051 - sets up the websockets so that incomings messages go to each client except the one that sent the original message - provides an index file at the root of the flask server that contains an example page (at http://localhost:5000/ that you can load multiple times to see the communication take place - Note that the way I'm excluding the client that sends the original message might not work all the time. I've seen it not send to other clients as well. Not sure about the behavior. If you have problems, see the note below about how to send to every client (including the one that sent the original message). (Maybe a single browser can use the same web socket for multiple tabs? If you know, let me know on [Twitter](https://twitter.com/TheIdOfAlan ))
Code
#!/usr/bin/env python3
=
=
=
=
=
### Flask Stuff
=
=
+= f
+=
return
### Websocket stuff
=
=
await
await
await
await
await
=
=
If you want the messages to be sent to all clients (including the one that originally sent the message), then change this:
Code
=
await
to this:
Code
=
await
That's it. Happy Web Socketing!