python - 如何在循环中通过 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 新手,没有一个有效。
有什么建议吗?谢谢!
解决方案
推荐阅读
- c# - 在两个实例化对象之间均匀实例化块
- node.js - 如何使用 jest 模拟这个 http 请求?
- git - bitbucket 中的 PR 差异
- javascript - 从 Vue 中的其他 js 文件调用 store.js 中的函数
- node.js - 带有 react 和 websockets 的应用程序的 Webpack 配置
- git - 安装 Big Sur 后,无法再通过 HTTPS git clone large repos
- android - AppBar 不使用嵌套的 ViewPager2 滚动
- c# - ZKTeco SDK ReadAllUserID() 失败,错误 -115
- postgresql - 登录尝试失败次数过多后如何重新启用 Azure Postgresql 数据库用户
- reactjs - 使用 useEffect 的 searchFilter