下面是一个简单的示例,演示如何连接到SocketIO服务器并在该连接上接收来自服务器的消息。
应用程序pyfrom flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@socketio.on('connect')
def connect():
emit('message', {'hello': "Hello"})
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
模板/index.html
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(data) {
console.log(data);
});
编辑:
要让服务器每五秒钟发送一条socketio消息,可以使用后台线程:
应用程序pyfrom flask import Flask, render_template
from flask_socketio import SocketIO, emit
import time
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None
def background_thread():
while True:
socketio.emit('message', {'goodbye': "Goodbye"})
time.sleep(5)
@socketio.on('connect')
def connect():
global thread
if thread is None:
thread = socketio.start_background_task(target=background_thread)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)