【问题标题】:Callbacks are not supported when broadcasting python-socketio广播 python-socketio 时不支持回调
【发布时间】:2020-11-05 07:23:54
【问题描述】:

我有这段代码,每当用户访问这个特定端点时,它应该向 python 客户端发送一条消息,然后获取一些数据,然后将其作为回调返回,这样我就可以向用户显示数据.

这是服务器端代码(NodeJS):

app.get('/hueapi/lights', verifyToken, (req,res) => {
  const bridgeIDFromApp = req.header('bridgeID');
  const socketID = socketRefDic[bridgeIDFromApp]['socketID'];
  io.to(socketID).emit('getAllLights', 'getAllLights', function(data){
      res.send(data); // The callback function that shows the data given by the python client
  });
});

它只是向有问题的 python 客户端发送一个简单的“getAllLights”消息,然后运行提供数据的函数。

这是客户端代码(python):

def getAllLights(data):
    lightData = requests.get('http://localhost:4000/lights/')
    return lightData

我的回拨是错误的还是?我只想在检索数据后直接将数据发送回给用户。

编辑:

我现在使用 io.to(...).emit(...) 而不是 io.send(...).emit(...) 但我仍然收到错误消息说我正在广播,但我不是,是吗?

【问题讨论】:

  • 回调或“确认”不支持广播
  • @Marc 我没有做广播,我正在向特定的套接字发送一些东西不是吗?
  • 在标题中你说“在命名空间广播”并调用io.send(...) 所以它是一个广播;)编辑:io.send 方法记录在哪里?!
  • @Marc 那么我如何通过对特定套接字/客户端使用回调来实现相同的目标呢?有没有可能,我什至发现很难找到发送特定套接字数据的正确语法,有很多答案说不同的事情。
  • 现在有广播中的 ack 回调方法。如果需要,您可以自己实现。

标签: javascript python node.js sockets socket.io


【解决方案1】:

我不认为 ack 方法对你有用,除非它也在 python 端实现。您仍然收到广播错误的原因是因为io.to 没有返回套接字,而是返回了一个进行广播的房间。

在客户端有一个单独的端点可能更容易。从我看到的内容来看,您的 python 代码甚至都没有尝试过。 python 代码应该仍然能够写入套接字。

因此,要实现自己的 ack 函数,您只需将 ack 消息写入套接字即可。如果你需要它有状态的命名空间,那么你必须包含一个地址供 python 代码引用你的getAllLights 消息。

节点:

app.get('/hueapi/lights', verifyToken, (req,res) => {
  const bridgeIDFromApp = req.header('bridgeID');
  const socketID = socketRefDic[bridgeIDFromApp]['socketID'];
  const uniqAck = "some unique endpoint path";
  
  const socket = getSocketByID(socketID);
  socket.on(uniqAck, (data) => res.send);
  socket.emit('getAllLights', 'getAllLights:'+uniqAck);
});

Python:

def getAllLights(data):
    lightData = requests.get('http://localhost:4000/lights/');
    return (lightData, split(data, ":")[1]); // split if its not already done by this point.

// capture 'value' from getAllLights when it is called...
socket.emit(value[1], value[0]); 

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多