socketio.emit() 当收到 UDP 数据包时

socketio.emit() when UDP packet received

我有一个 flask-socketio 服务器,它提供在网页上显示接收到的消息的索引。服务器在自己的线程中通过 ZMQ 或基本 UDP 接收消息。在相同的线程中,它向网页发送消息,但只收到 ZMQ 线程消息。你能告诉我为什么 UDP 线程 eimtting 不起作用吗?

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。

问题实际上出在 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 订阅不是独占的,新旧线程都可以启动,新线程将能够毫无问题地将消息中继到新的 socketio。

总的来说,线程和重新加载器的交互比较混乱,另见https://github.com/miguelgrinberg/Flask-SocketIO/issues/567

指定debug=Falsedebug=True, use_reloader=False即可避免该问题。