Skip to content

A little bit more accurate data channel example #8

@nnseva

Description

@nnseva

The data channel example shown in the tutorial http://rtc.io/tutorial-rtc-text-chat.html has some inaccurate code which causes wrong example behaviour in case of 3 or more nodes in the chat. Particularly, when the second channel is created, the message.onkeyup function which was initialized before, is reinitialized by the just created function:

    messages.onkeyup = function () {
        channel.send(this.innerHTML);
    };

Such a bug in the tutorial makes imaging of your RTC package worse.

I suggest the following a little bit more precise code to replace a tutorial code. This code creates a channel registry which is updated by two different session channel-related events, and allows to create as many nodes in the chat, as simultaneous channels allowed in the RTC implementation.

    // Set RTC options
    var rtcOpts = {
        room: 'test-data',
        signaller: '//switchboard.rtc.io',
        capture: false,
    };

    // call RTC module
    var rtc = RTC(rtcOpts);

    // A contenteditable element to show our messages
    var messages = document.getElementById('messages');

    // Channels registry
    var channels = {};

    // Send message to every registered channel
    messages.onkeyup = function () {
        for(var i in channels) {
            channel = channels[i];
            channel.send(messages.innerHTML);
        }
    };

    // Bind to events happening on the data channel
    // and fill the channel registry
    function bindDataChannelEvents(id, channel, attributes, connection) {
        channels[id] = channel;

        // Receive message
        channel.onmessage = function (evt) {
            messages.innerHTML = evt.data;
        };
    }

    // Clean channel registry for closed channels
    function unbindDataChannelEvents(id, channel, name) {
        delete channels[id];
    }

    // Start working with the established session
    function init(session) {
        session.createDataChannel('chat', {
            ordered: true,
            maxRetransmits: 12
        });
        // Bind to important session events
        session.on('channel:opened:chat', bindDataChannelEvents);
        session.on('channel:closed:chat', unbindDataChannelEvents);
    }

    // Detect when RTC has established a session
    rtc.on('ready', init);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions