【发布时间】:2018-09-16 21:36:32
【问题描述】:
我是 Flask 的新手,我的 Javascript 有点生疏。我需要在外部在 python 中生成事件并将它们实时推送到网页,所以我选择了 Flask-SocketIO。我已经构建了我能想到的最简单的示例:
from flask_socketio import SocketIO, emit
from flask import Flask, render_template
from time import sleep
from threading import Thread, Event
app = Flask(__name__)
app.config['SECRET_KEY'] = 'haha!'
app.debug = True
socketio = SocketIO(app)
thread = Thread()
thread_stop_event = Event()
class MyThread(Thread):
def __init__(self):
super(MyThread, self).__init__()
def ticker(self):
print("ticking")
while not thread_stop_event.isSet():
text="hi there"
print(text)
socketio.emit('message', {'data': text})
sleep(1)
def run(self):
self.ticker()
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def test_connect():
global thread
print('Client connected')
if not thread.isAlive():
print("Starting Thread")
thread = MyThread()
thread.start()
@socketio.on('disconnect')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app)
在模板目录中使用这个 index.html 文件:
<html>
<head>
<title>Ticker</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function() {
socket.send('User has connected!');
});
socket.on('message', function(text) {
$("#messages").append('<li>'+text+'</li>');
console.log('Received message');
});
});
</script>
<ul id="messages"></ul>
</body>
</html>
我在控制台中看到了“你好”的列表,但在浏览器中的 localhost:5000 没有任何内容。它似乎挂了 - 浏览器底部显示“等待缓存”或“等待本地主机”。有人能弄清楚我做错了什么吗?提前非常感谢!
【问题讨论】:
标签: javascript python html flask socket.io