首页 > 解决方案 > 如何在循环中通过 DataChannel 发送消息

问题描述

我有一个关于使用 WebRTCbin 在 Python 中编程的问题。所以channel.connect('on-open', self.on_data_channel_open)是一个事件监听器,当通道的状态变为打开时触发,然后调用回调函数on_data_channel_open。我使用了一个 for 循环来遍历日志数据,并且我希望在循环内发送每个日志。channel.emit('send-string', str(log))是通过数据通道发送消息的代码。但是,只有在整个循环完成时才会发送消息。

def on_data_channel(self, webrtcbin_object, channel):
    """
    This is a call back function when a data channel is created
    """
    print('data_channel created')
    channel.connect('on-error', self.on_data_channel_error)
    channel.connect('on-open', self.on_data_channel_open)
    channel.connect('on-close', self.on_data_channel_close)
    channel.connect('on-message-string', self.on_data_channel_message)
    print(f'The datachannel state is {channel.ready_state}')
    
def on_data_channel_open(self, channel):
    print('{} data_channel opened'.format(self.camera_id))
    self.sendlog(channel)

def sendlog(self, channel):
    try:
        with open('data.txt') as f:
            json_data = json.load(f)
    
        for log in json_data:
            print(channel.ready_state)
            if channel.ready_state == 2:
                print(f'sending the log: {log}')
                channel.emit('send-string', str(log))
                time.sleep(0.33)
            else:
                break
    except (FileNotFoundError, JSONDecodeError) as ex:
        print("dealing file encouter error: {}; error is {}".format(ex, type(ex)))

我在执行消息发送时看到数据通道的缓冲区增加了。我猜所有的数据都进入了缓冲区,DataChannel对象通过通道将整个缓冲区发送给了接收者。

我尝试了几种异步发送消息的方法,但我是 python 新手,没有一个有效。

有什么建议吗?谢谢!

标签: pythonwebrtcgstreamer

解决方案


推荐阅读