Skip to content

Instantly share code, notes, and snippets.

@punchagan
Last active December 21, 2023 23:36
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save punchagan/53600958c1799c2dcf26 to your computer and use it in GitHub Desktop.
Save punchagan/53600958c1799c2dcf26 to your computer and use it in GitHub Desktop.
A simple Flask sockets example
# Copy of http://stackoverflow.com/a/20104705
from flask import Flask, render_template
from flask_sockets import Sockets
app = Flask(__name__)
app.debug = True
sockets = Sockets(app)
@sockets.route('/echo')
def echo_socket(ws):
while True:
message = ws.receive()
ws.send(message[::-1])
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/echo_test', methods=['GET'])
def echo_test():
return render_template('echo_test.html')
if __name__ == '__main__':
app.run()
<!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");
};
ws.onmessage = function(evt) {
alert(evt.data);
};
</script>
</head>
</html>
@motoom
Copy link

motoom commented Jul 20, 2017

Is it maybe an idea to implement auto-reconnect, when the connection drops?

@DanialGhofrani
Copy link

is this python3?

@efibutov
Copy link

Unfortunately, this won't work. I tried to build very small web-server as GUI for another background process. Of course, I wanted to see feedback from my app to appear immediately on the HTML-page. Websocket should do the work perfect, but flask_socket does not support WebSocket on the client side. Instead, your JS client should use io.connect Take a look here:

https://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent

@mpjeffin-gee
Copy link

Thanks for the snippet. It was very useful!

@dave-kitchen
Copy link

I hate to be stupid, but where does the 8000 come from?
It is the target port specified in the client-side call to /ws, but I don't see where the server is told to bind to it.

@maxbellec
Copy link

maxbellec commented Jul 22, 2020

The flask (dev) server returns a 404 on /echo, but it works by running a server with gunicorn: gunicorn -k flask_sockets.worker hello:app

@punchagan
Copy link
Author

Oh, wow, I didn't know this gist had any views, until GitHub now shows notifications for gists too.

@sabahath786
Copy link

Hi, I tried the same sample given, i am getting the following error in browser concole
Emulator.js:82 WebSocket connection to 'ws://127.0.0.1:5000/echo' failed: Error during WebSocket handshake: Unexpected response code: 404

@alexmclarty
Copy link

I've tried gunicorn and various other ways to make this work but I just get a 404.

@engelmav
Copy link

I've tried gunicorn and various other ways to make this work but I just get a 404.

Have you tried starting the flask app with gunicorn, using the parameter --worker-class flask_sockets.worker?

@engelmav
Copy link

Also, this is working for ping/pong, ws.handler.websocket.send_frame("HB", ws.OPCODE_PING)

    @sockets.route("/ws/stream")
    def websocket(ws):
        messages_backend.register(ws)
        while not ws.closed:
            message = ws.receive()
            LOG.debug(f"message: {message}")
            ws.handler.websocket.send_frame("HB", ws.OPCODE_PING)
            # Context switch while `MessagesBackend.start` is running in the background.
            gevent.sleep(1)

@davidhariri
Copy link

The flask_sockets project is now archived and unsupported. We @AdaSupport had issues running it with gunicorn. This snippet solved our problem:

# NOTE: https://stackoverflow.com/a/64002375/2114288
import grpc.experimental.gevent as grpc_gevent
grpc_gevent.init_gevent()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment