【问题标题】:Flask socketIO connection established but not routedFlask socketIO 连接已建立但未路由
【发布时间】:2020-10-29 01:18:04
【问题描述】:

对于我的项目,我必须将一个 socketIO 后端连接到另一个。为此,我正在使用 Flask-socketio 和 socketio-client。两者的代码如下:

客户:

from socketIO_client import SocketIO, LoggingNamespace
ip = '192.168.1.41'
port = 8090

def handle_aaa_response():
    print('response')

socketIO = SocketIO(ip, port)
socketIO.on('pingSuccess', on_aaa_response)
socketIO.wait(seconds=1)

服务器:

from flask import Flask, render_template, jsonify, Response
from flask_socketio import SocketIO, emit

TRACE_LIBRARIES = False
HOST = '0.0.0.0'
WEB_PORT = 8090
USE_PIN = False

def handle_connect():
        print('hello world')
        emit('pingSuccess')

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app, cors_allowed_origins="*")
socketio.on('connect', handle_connect)

try:
    socketio.run(app,
                    host=HOST,
                    port=WEB_PORT,
                    log_output=True)
except KeyboardInterrupt:
    print('*** User raised KeyboardInterrupt')
    exit()

当我运行客户端和服务器时,服务器只记录以下内容:

(4743) accepted ('192.168.1.33', 53500)
192.168.1.33 - - [21/Oct/2020 15:48:31] "GET /socket.io/?EIO=3&transport=polling&t=1603291711742-0 HTTP/1.1" 200 371 0.005033
(4743) accepted ('192.168.1.33', 53502)

这意味着服务器正在接受来自客户端的连接,但没有路由到服务器上的正确路由。

我想知道如何更改它以使其到达正确的路线并打印“hello world:

【问题讨论】:

    标签: python flask socket.io


    【解决方案1】:

    与您在client 脚本中使用的常规socketIO_client 包中的socketio.on() 相反,flask_socketio 使用.on() 作为decorator

    因此,要向flask_socketio 中的事件添加回调,您需要更改以下内容:

    ...
    socketio = SocketIO(app, cors_allowed_origins="*")
    
    
    @socketio.on('connect')
    def handle_connect():
        print('hello world')
        emit('pingSuccess')
    ...
    

    【讨论】:

    • 接受这个答案,因为它解释了我的代码为什么错误以及如何正确执行。干杯。
    【解决方案2】:

    服务器端

    @socketio.on('connect')
    def test_connect():
        print('hello world')
        emit('pingSuccess')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2016-06-13
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2020-07-07
      相关资源
      最近更新 更多