烧瓶套接字IO连接已建立但未路由

时间:2020-10-21 15:01:55

标签: python flask socket.io

对于我的项目,我必须将一个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:

2 个答案:

答案 0 :(得分:1)

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

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

...
socketio = SocketIO(app, cors_allowed_origins="*")


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

答案 1 :(得分:0)

服务器端

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