我有一个flask-socketio服务器,该服务器提供在网页上显示收到的消息的索引。服务器通过自己的线程通过ZMQ或基本UDP接收消息。在同一线程中,它将消息发送到网页,但仅接收到ZMQ线程消息。您能告诉我为什么UDP线程枚举不起作用吗?
from flask import Flask, request
from flask_socketio import SocketIO, emit
from threading import Thread
import socket
import time, zmq, pmt
HTTP_PORT = 5000
ZMQ_PORT = 5001
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
app = Flask(__name__, static_url_path="")
# app.config["SECRET_KEY"] = "secret!"
socketio = SocketIO(app)
def background_thread():
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
message = 'hello'
socketio.emit('gnu radio', (message,))
time.sleep(0.10)
print "received message:", data
def background_thread_2():
# Establish ZMQ context and socket
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, "")
socket.connect("tcp://0.0.0.0:%d" % (ZMQ_PORT))
while True:
# Receive decoded ADS-B message from the decoder over ZMQ
pdu_bin = socket.recv()
pdu = str(pmt.deserialize_str(pdu_bin)).decode('utf-8', 'ignore').encode("utf-8")
message = 'hello2'
socketio.emit('gnu radio', (message,))
time.sleep(0.10)
@app.route("/")
def index():
return app.send_static_file("index.html")
@socketio.on("connect")
def connect():
print("Client connected", request.sid)
@socketio.on("disconnect")
def disconnect():
print("Client disconnected", request.sid)
if __name__ == "__main__":
thread = Thread(target=background_thread)
thread.daemon = True
thread.start()
thread = Thread(target=background_thread_2)
thread.daemon = True
thread.start()
socketio.run(app, host="0.0.0.0", port=HTTP_PORT, debug=True)
仅收到Hello2。
答案 0 :(得分:0)
问题实际上出在Flask的重新加载器上。
启用调试模式后,默认情况下,Flask将使用重新加载程序-该过程监视您应用程序的文件并在文件更改时重新启动服务器。因此,当Flask运行socketio.run
行并确定应启用调试模式时,它重新运行脚本。
这意味着您的后台线程将再次启动。但是您已经有一个绑定到UDP 127.0.0.1:5005的正在运行的线程。这样做的第二次尝试将失败:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\matejcik\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\matejcik\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File ".\app.py", line 23, in background_thread
sock.bind((UDP_IP, UDP_PORT))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
旧的UDP线程仍然存在,将接收UDP消息并将其打印到控制台。 但是,该线程在重新启动之前仍然引用旧的Python环境,因此socketio实例已过时,将消息发送到void。
这也是ZMQ可以很好地接收消息的原因:因为ZMQ订阅不是唯一的,所以旧线程和新线程都可以启动,而新线程将能够将消息中继到新套接字,而不会出现问题。
通常,线程和重新加载器的交互比较混乱,另请参见https://github.com/miguelgrinberg/Flask-SocketIO/issues/567
如果指定debug=False
或debug=True, use_reloader=False
,则可以避免此问题。