Peer to peer Chat

Here is a description of the different steps to exchange instant messaging between two users using apiRTC

Create and register a UserAgent

Check our tutorial on registration if needed to create the userAgent and register.

Select a contact to start a chat

Once your user agent is registered, you will be able to comunicate with other contacts via the session object

        $('#start-chat').on('click', function(e) {
            // Get contact from it's id
            var contactId = document.getElementById('contact-id').value;
            if (contactId !== '') {
                activeContact = connectedSession.getContact(contactId);

Send a message to the contact

Now you can send the message to the contact. NOTE: The contact needs to be online in order for them to receive the message

        $('#message-list').append('<li><b>Me</b> : ' + message + '</li>');
        //Actually send message to active contact
            .then(function() {
                //Message successfully sent!
            .catch(function(err) {
                //An error occured...
                $('#message-list').append('<li><i>* Could not send message to contact : "' + message + '", ' + err.error.message +  ' *</i></li>');

Listen for contacts' messages

You can listen for incoming messages through the Session#contactMessage

        //Listen to contact message events globally
        connectedSession.on('contactMessage', function(e) {
            //Display message in UI
            if (e.sender === activeContact) {
                $('#message-list').append('<li><b>' + e.sender.getId() + '</b> : ' + e.content + '</li>');

Alternatively, you can also listen for incoming messages of a specific contact through the Contact#message event

Live Demo