Reputation: 554
i'm trying to implement very basic usage of flask_socketio to send some data to client. The code is following:
server.py:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
socketio = SocketIO(app)
@app.route('/')
def index():
socketio.emit('my_data', 'yay', broadcast=True)
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
index.html:
{% extends 'base.html' %}
{% block content %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log('Websocket connected!');
});
socket.on('my_data', function(data) {
console.log(data);
});
</script>
{% endblock %}
When doing python server.py
, i'm getting Websocket connected! in the browser console, but that's all, with no further output.
I've tried that eventlet trick by pasting following code to the beginning of server.py, but this didn't help:
import eventlet
eventlet.monkey_patch()
socketio = SocketIO(app, async_mode='eventlet')
Any ideas?
Upvotes: 0
Views: 674
Reputation: 67479
What did you expect to happen? Your Flask application is calling socketio.emit()
before the client receives the index.html
template, which has the code that establishes the Socket.IO connection, so at the time the emit runs there is no connection yet.
If you wanted that emit to work you would need to have a client connected, and then connect from a second client. When client #2 connects the socketio.emit()
call will be received by client #1, which is already connected.
Upvotes: 2