[英]How do you send messages from Flask server (Python) to HTML client?
为了练习,我试图让Flask服务器不断地将“Hello”打印到HTML页面的控制台。 我现在迷失了如何继续。
目前,我的服务器代码看起来像这样
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@socketio.on('message')
def handle_message(message):
print('Message: ' + message)
send(message)
@socketio.on('json')
def handle_json(json):
send(json, json=True)
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json, broadcast=True)
def hello():
emit('message', {'hello':"Hello"})
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app)
while True:
hello()
虽然我的客户端代码如下所示:
<head>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.emit('connected');
});
socket.on('message', function(data) {
console.log(data);
});
</script>
</head>
但是我的控制台日志中没有得到任何内容。 如何让它将Flask服务器发送的消息打印到控制台? 我究竟做错了什么?
我现在明白,它应该打印JSON而不是“Hello”字符串,这也没关系。 我只想从服务器上在Web控制台上打印一些东西。
这是一个简单的示例,说明如何连接到SocketIO服务器并在该连接上从服务器接收消息。
app.py
from 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的
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(data) {
console.log(data);
});
</script>
</head>
编辑:
要让服务器每五秒钟发送一次socketio消息,您可以使用后台线程:
app.py
from 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.