[英]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.