Android P2P Chat Web-RTC

What we would be building

Web RTC
WebRTC is an open source project to enable realtime communication of audio, video and data in Web and native apps. So as a result we would be using webRTC to create peer to peer connection and then using data channels to create a chat app.
Signalling server
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
STUN and TURN servers
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 in the real world explains in more detail.)
General Flow for P2P connections

Code for Signalling server
We would simply create a Node Server, which would act as signalling server since it uses web sockets
What is SDP?
SDP stands for Session Description Protocol, and it plays a vital role in WebRTC (Web Real-Time Communication) for negotiating and establishing peer-to-peer connections between devices. SDP is a text-based protocol that describes the multimedia capabilities and session parameters of participants in a communication session.
A brief from code and diagram



Let’s get started
Dependencies
Connection with web socket
We would be emitting SocketEvents
via sharedFlow
ViewModel, States and Actions
Rest of Implementation and gotchas
RTC peer connection creation
In accordance with our code of client 1 and client 2,
- client 1 would create RTC peer object when it decided to call client 2
- but client would create RTC peer object when it receives offer from client 1, and decides to accept it
This is denoted by cold start on below diagram

WebRTCManager
All webRTC related things are delegated to this class see code in github repo, like
- setting up data channels
- answer to any p2p offer
- setting remote session SDP to incoming SDP from socket
- creating a brand new offer
- create data channels, and send exposing received from peer connection’s data channel as sharedFlow
Handling own’s send message
Unable to see own’s sent message in UI Activity, as a workaround emitted message in shared flow directly. You know a better solution, please do drop a comment.
Code
Full code can be found here
Resources
Originally published here on April 4, 2024.