How to send messages through DataChannel within a loop

Viewed 96

I got a question about programming in Python with WebRTCbin. So the channel.connect('on-open', self.on_data_channel_open) is an event listener that is triggered when the channel’s state changes to open, then the callback function on_data_channel_open is called. I used a for loop to loop through the log data and I was expecting to send each log inside the loop. channel.emit('send-string', str(log)) is the code to send messages through the data channel. However, the messages only are sent when the whole loop is finished.

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)))

I saw in the Datachannel's buffer was increased while the message send was executed. I guess all data have entered the buffer, and the DataChannel object sent the entire buffer to the receiver through the channel.

I have tried a few ways to async the message sending, but I am new to python, none of them were worked.

Are there any suggestions? Thanks!

0 Answers
Related