Realtime Communication With WebRTC Using Node.js & Socket.IO

WebRTC is an open source project to enable real-time communication of audio, video and data. WebRTC is available for native apps (iOS & Android) and web browsers (Firefox, Opera and Chrome on desktop & Android).

WebRTC enables peer to peer communication but it still needs a server for the following reasons,

  • Signaling – Exchange metadata for communication between peers.
  • STUN and TURN – Discover paths between peers on the Internet.


WebRTC uses RTCPeerConnection to communicate streaming data between browsers, but also needs a mechanism to coordinate communication and to send control messages, a process known as signaling. Signaling methods and protocols are not specified by WebRTC. In this article we are using Socket.IO for messaging.


WebRTC is designed to work peer-to-peer, so users can connect by the most direct route possible. However, WebRTC is built to cope with real-world networking: client applications need to traverse NAT gateways and firewalls, and peer to peer networking needs fallbacks in case direct connection fails. As part of this process, the WebRTC APIs use STUN servers to get the IP address of your computer, and TURN servers to function as relay servers in case peer-to-peer communication fails.


WebRTC has several JavaScript APIs,

  • getUserMedia(): capture audio and video.
  • MediaRecorder: record audio and video.
  • RTCPeerConnection: stream audio and video between users.
  • RTCDataChannel: stream data between users.

How It Works?

  • Signaling : both peers connect to a signaling server (using websockets over 80/443, comet, SIP,etc..) and exchange information (about their media capabilities, public IP:port pairs when they become available, etc.)
  • Discovery : Devices connected to LAN or mobile networks are not aware of their public IP (and port) where they can be reached at so they use STUN/TURN servers located on the public Internet to discover their ip:port pair (ICE candidates). In the process they punch a hole through the NAT/router which is used in step3:
  • P2P connection : once the ICE candidates are exchanged through the initial signaling channel each peer is aware of each other’s ip:port (and holes have been punched in NATs/routers) so a peer to peer UDP connection can be established.


Code Snippet below takes a photo and share it via a data channel to another peer and also the copy of photo will be saved on the server.



Please leave your valuable comments/suggestions/feedback on below comment box if any.

Thank You !!

Siva Sankar

SIVA SANKAR, Working as a Software Engineer, Blogging is my hobby. I completed my Bachelors of Engineering (Computer Science Engineering) in Chennai, India. and my Master of Engineering (Embedded System Technologies) in Tamilnadu, India.

Leave a Reply

Your email address will not be published. Required fields are marked *