I am playing around with websockets in order to see if I can replace polling updates to a project. I am using Flask-Sockets and I want to emit an update through a Flask view.
For example
from flask import Flask
from flask_sockets import Sockets
app = Flask(__name__)
sockets = Sockets(app)
@sockets.route('/echo')
def echo_socket(ws):
while True:
message = ws.receive()
ws.send(message)
@app.route('/')
def hello():
# here I want to emit a message like ws.send(message)
return 'Hello World!'
I looked around and I didnt find anything similar. Is this thing possible?
THIS IS VERY VERY SIMPLE DEMO EXAMPLE
In the below example, on every 2 seconds, the server send message to the client with updated count. First parameter of emit function tells which function to call on client side.
app.py
On your client side you will have to use this. In this example I have included CDN. Similarly for demo purpose I have used jquery.
templates/index.html
When you run this using
python app.py
, and visit http://127.0.0.1:5050, then you should see the sockets in action.A working version of the demo is available here