socketio.client 监听服务器

时间:2021-02-02 23:31:14

标签: reactjs socket.io flask-socketio

如何在 node.js 上的 React 框架内使用 socket.io-client 监听服务器?

useEffect(() => {
    const socket = socketIOClient(ENDPOINT);

    socket.on('ctime', function (data) {
        console.log('ctime: ' , data)
    })
})

flask 服务器发出消息:

@socketio.on('time')
def ctime():
    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M:%S")
    send(current_time)

while True:
    ctime()
    time.sleep(1)

怎么了?客户端应该监听和消费flask服务器发送的消息

1 个答案:

答案 0 :(得分:1)

客户端内的套接字正在侦听服务器发出的 "ctime" 事件。服务器正在侦听要由客户端发出的 "time" 事件,然后发送 "message" 事件。

尝试将Client中的"ctime"改为"message",或者将Server中的send(current_time)函数改为emit('ctime', current_time)

我以前从未使用过flask,所以如果我遗漏了什么,我很抱歉。