flask_socketio已连接到客户端,但未收到消息

问题描述 投票:1回答:1

我有一个Flask服务器应用程序/ React客户端应用程序,我正在尝试将flask_socketio集成到其中。我已经复制了flask_socketio文档中的标准介绍性示例,并且可以在我的React前端正常工作。

但是,当我尝试在烧瓶中复制结果时,使用完全相同的步骤,我无法发送或接收消息。运行烧瓶应用程序时,我可以看到客户端已连接输出,在浏览器控制台中,我有一个console.log告诉我我已连接到服务器,但是发出(或发送)消息似乎不起作用。介绍示例的方式。

我已经安装了eventlet,文档说flask_socketio应该自动识别此事件。以下是一些代码段供参考。

app / socket / __ init __。py


from flask_socketio import SocketIO

socketio = SocketIO(cors_allowed_origins='http://localhost:3000')

app / socket / socket.py


from flask_cors import cross_origin
from flask_socketio import send, emit

from . import socketio

@cross_origin
@socketio.on('connect')
def handle_connection():
    print('a user has connected')
    emit('mymessage', 'Hi client, I am server.') # I've tried `send` here too

@cross_origin
@socketio.on('mymessage')
def handle_message(message):
    print('Message from client: ' + message)

app / __ init __。py

from flask import Flask
from flask_cors import CORS

from .socket import socketio


def create_app():
    app = Flask(__name__)

    # Cross Origin Resource Sharing
    CORS(app)

    # Socket.IO
    socketio.init_app(app)


    return (socketio, app)

app / app.py


from . import create_app

socketio, app = create_app()

if __name__ == '__main__':
    socketio.run(app, host='localhost', port=5000)
    #app.run("0.0.0.0", port=5000, threaded=True, use_reloader=False)

反应成分

const socket = io('http://localhost:5000');

class Figures extends React.Component {

  setSocketListeners () {

    socket.on('connect', () => {
      console.log('connected to socket');
      socket.emit('mymessage', 'Hi server, I am client.');
    })

    socket.on('mymessage', function(data) {
      console.log('Message from server: ' + data)
    })
  }

  componentDidMount() {
    this.setSocketListeners()
  }

...

输出:

终端

 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 216-814-307
(4089) wsgi starting up on http://127.0.0.1:5000
127.0.0.1 - - [14/Aug/2019 02:40:35] "POST /socket.io/?EIO=3&transport=polling&t=MoEsrSZ&sid=a4f73c34553f478cabde2f919b48fe98 HTTP/1.1" 200 219 0.002675
(4089) accepted ('127.0.0.1', 36512)
(4089) accepted ('127.0.0.1', 36514)
127.0.0.1 - - [14/Aug/2019 02:40:36] "GET /socket.io/?EIO=3&transport=polling&t=MoEsrSf&sid=a4f73c34553f478cabde2f919b48fe98 HTTP/1.1" 200 235 1.612156

浏览器

connected to socket

编辑:

初步调试似乎表明这是'create_app()'的问题。参见@miguelgrinberg的link。但是,在解决此问题上仍然没有进展。

已在flask中启用socketio.init_app(app, async_mode="eventlet", engineio_logger=True)并已禁用调试,以确保未使用werkzeug。

python flask socket.io flask-socketio
1个回答
0
投票

与类似的问题有关here

我认为您应该在前端代码上打开套接字时启用到WebSocket的传输模式,例如:

    const socket = io('http://localhost:5000', {transports: [websocket]});

此外,您还需要安装gevent和gevent-websocket并导入socket.io-client,如:

    import io from 'socket.io-client/dist/socket.io'; 

我已经实现了一个工作示例:https://github.com/roj4s/webicami

© www.soinside.com 2019 - 2024. All rights reserved.