-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

WebRTC Cookbook
By :

In this recipe, we will cover the process of implementing private, peer-to-peer web chat using signaling server as the middle point. Peers will send chat messages via the signaling server. In the schema represented in the following diagram, you can see the flow:
To implement the chat feature via the signaling server, we need to add some methods to the client code with the following steps:
function processSignalingMessage(message) { var msg = JSON.parse(message); if (msg.type === 'CHATMSG') { onChatMsgReceived(msg.value); } else if (msg.type === 'offer') { pc.setRemoteDescription(new RTCSessionDescription(msg)); doAnswer(); } else if (msg.type === 'answer') { pc.setRemoteDescription(new RTCSessionDescription(msg)); } else if (msg.type === 'candidate') { var candidate = new RTCIceCandidate({sdpMLineIndex:msg.label, candidate:msg.candidate}); pc.addIceCandidate(candidate); } else if (msg.type === 'GETROOM') { room = msg.value; onRoomReceived(room); } else if (msg.type === 'WRONGROOM') { window.location.href = "/"; } };
CHATMSG
type and if so, we will call the onChatMsgReceived
method to process it:function onChatMsgReceived(txt) { var chatArea = document.getElementById("chat_div"); chatArea.innerHTML = chatArea.innerHTML + txt; chatArea.scrollTop = chatArea.scrollHeight; };
Here, we will get the chat_div
element by its ID and alter its content by adding the chat message received from the remote peer via the signaling server.
function chatSendMessage(msg) { if (!channelReady) return; sendMessage({"type" : "CHATMSG", "value" : msg}); };
This function checks whether the WebSocket channel is up and sends a chat message to the signaling server using the channel. To use this function, we can use the HTML input tag with the submit
button and call it on the submit
event.
The basic principle of this solution is pretty simple:
CHATMSG
typeCHATMSG
type and if so, shows it to the userTo distinguish chat messages from WebRTC messages, you can use any word to mark the message type. It can be CHATMSG
or whatever you prefer.
This way of implementing web chat is usually not secure because the data will go via the signaling server and not directly through the peers. Nevertheless, it is suitable for public chat rooms where there can be several people at a time. For private peer-to-peer chats, it is usually better to use WebRTC data channels, and that way it is more secure.
Change the font size
Change margin width
Change background colour