WebRTC Data Channels

As we have seen in the class, WebSockets are powerful! We can enable real time interaction in the browser with other clients via a server.

Unfortunately, this last part, "via a server" does create a limitation. A server is required with enough bandwidth and horsepower to handle the data that clients would like to share.

We have also seen in class the power of Peer to Peer audio and video transmission via WebRTC. Having the ability to transfer audio/video directly from one user to another reduces latency, removes the need to have a server located in a high bandwidth environment and basically opens the doors to a wide range of potential application ideas without a lot of cost.

Fortunately, the same thing is now possible with non-audio/video data via the RTCDataChannel API, part of WebRTC.

More information: HTML5Rocks: WebRTC DataChannels

Peer.js

As with WebRTC for audio and video, the peer.js library makes working with DataChannels much easier.

Here is a quick example:
<html>
	<head>
		<script src="peer.min.js"></script>
		
		<script type="text/javascript">
			var mypeerid = null;
			var peer = null;
			var connection = null;
			
			var init = function() {
				peer = new Peer({host: 'liveweb.itp.io', port: 9000, path: '/'});
				
				peer.on('open', function(id) {
				  console.log('My peer ID is: ' + id);
				  mypeerid = id;
				});
				
				peer.on('connection', function(conn) {
					connection = conn;
					connection.on('open', function() {
						document.getElementById('chatlog').innerHTML += "Connection Established";
					});
					connection.on('data', function(data) {
						document.getElementById('chatlog').innerHTML += data;
					});
				});
			};	
			
			var sendmessage = function() {
				connection.send(document.getElementById('chat').value);
				document.getElementById('chat').value = "";
			};

			var placecall = function() {
				connection = peer.connect(document.getElementById('other_peer_id').value);
				connection.on('open', function(data) {
					document.getElementById('chatlog').innerHTML += "Connection Established";
				});

				connection.on('data', function(data) {
					document.getElementById('chatlog').innerHTML += data;
				});
			};	
		</script>
	</head>
	
	<body onload="init()">
		<input type="text" id="other_peer_id" value="PeerID to Call">
		<input type="button" value="Call" onclick="placecall()"><br />
		<input type="text" id="chat">
		<input type="button" value="Send" onclick="sendmessage()"><br />
		<div id="chatlog"></div>
	</body>
</html>
Try it

Another Example