Posted by Sunidhi Sharma | Last Updated: 09-Jan-19
WebRTC is an open source project which enables a real-time communication of media as well as data across peers. WebRTC establishes a peer to peer connection framework which is used to share high-quality video among Android, iOS, and Web. For web, WebRTC is quite simple. There is a certain set of APIs which one can call to get user's media and data.
However, in Android, for this to work, we need to make an addition, i.e.; add the peer connection library in your project and connect the devices using peer connection.
This blog-post discusses how can one send data across the devices connected with WebRTC which will easily let them develop chat applications or to send messages even when the call is taking place without breaking the connection.
- Android Studio with Gradle > 3.0
Step 1: Adding the dependencies
Add the following dependencies in your project level build.gradle file:
You can also import this library as a module in the project.
Step 2: Adding the UI for the application.
Step 3: Initializing the Peer Connections.
Before proceeding forward, we need to know what a peer connection is. Firstly, a peer is a device which is connected to a network and peer to peer connection is an architecture which helps and connects two or more devices so that they can share their resources without going through the trouble of connecting to a separate server.
Step 4: Sending and Receiving the text messages
Sharing of data can only be possible when the network through which they are connected allows it, to facilitate this we use STUN and TURN server. Generally, we need signaling to connect two or more devices. Signaling is used to let peers know that there is a connection between them.
Since,we are not using any signaling server this time so we just use the same device as both peers, we will send the data to the same device using Data Channel API. What we are going to do is:
- Send the data from our device to the data channel. For connecting peers, we need signaling to connect two or more devices. Since we are not using
signalingserver in this demo, we will send the data to the same device using Data Channel API.
- Display the data received from the data channel to a text box.
Sending text messages
Receiving text messages
To summarize, we can easily send texts as well as files using the webRTC’s data channel API. Since there’s no signaling server used you are just looping the messages back to yourself. But, once you use this code with some signaling server (choice for signaling is yours: you can either use API’s or WebSocket) you can easily send data to all the different devices connected across the network in the same room (aka peers).