In this article we are going to learn how we can use the TURN server with the PeerJS
For this, we are going to create a new PeerJs project
This is going to be a simple webrtc application for learning purposes.
The App is going to connect to another peer using PeerJs and send messages, we are going to use TURN server to bypass the NAT in this example.
For a TURN server we are going to use the Metered TURN servers
Here is what we are going to learn in this article
Getting a TURN server solution (Metered TURN servers)
Setting Up a Simple WebRTC Project Using PeerJS
Integrating Metered TURN servers with PeerJs project
Testing the TURN server and the app
In order to integrate TURN server with PeerJs application, you first need a TURN server.
In order to make things easier, we are going to use the Metered TURN service in this example
Step 1: Create a Free account
go to the Metered TURN server website:
You can click on the instructions button to know more about the how to use the credential in your app
UI Elements and Connection Handling
const peerIdInput = document.getElementById('peerId');
const otherPeerIdInput = document.getElementById('otherPeerId');
const connectButton = document.getElementById('connectButton');
const messageInput = document.getElementById('message');
const sendMessageButton = document.getElementById('sendMessageButton');
const messagesDiv = document.getElementById('messages');
let dataConnection = null;
- You get the elements from the index.html page like peer ID, input messages etc
dataConnectionis initialized with null
Displaying the Peer ID
peer.on('open', id => {
peerIdInput.value = id;
});
Here the peer js listner waits for the open event. when the peer ID is ready, the id is displayed in the peerIdInput field.
Establishing a Connection
connectButton.addEventListener('click', () => {
const otherPeerId = otherPeerIdInput.value;
if (!otherPeerId) {
alert('Please enter the other peer ID.');
return;
}
dataConnection = peer.connect(otherPeerId);
setupDataConnectionEvents();
});
- When the user clicks on the Connect button, the script to establish a connection to the perr whose ID is entered in the
otherPeerInputfield runs - It calles the
peer.connectand passes the other peer's ID and assigns the returned data connection object todataConnection
setupDataConnectionEventsis called to initiaze event listners for the new connection
Sending Messages
sendMessageButton.addEventListener('click', () => {
const message = messageInput.value;
if (!message) {
alert('Please enter a message to send.');
return;
}
if (dataConnection && dataConnection.open) {
dataConnection.send(message);
displayMessage(`You: ${message}`);
messageInput.value = '';
} else {
alert('Data connection is not established. Please connect to a peer first.');
}
});
- Here we are listning on the
Send messagebutton. If something is typed in the input field and the connection is established we send the message - The sent messages are also displayed on the
messagesDivafter theYou:text and the input is cleared
Receiving Connections and Messages
peer.on('connection', connection => {
dataConnection = connection;
setupDataConnectionEvents();
});
Nest we are listning for the connections when another peer connects to this peer then we save the connection object in the dataConnection variable and similar to outgoing connections the event listners are setup by the library
Handling connection events
function setupDataConnectionEvents() {
dataConnection.on('data', message => {
displayMessage(`Peer: ${message}`);
});
dataConnection.on('open', () => {
messagesDiv.innerHTML += '<p>Connection established. You can send messages now.</p>';
});
dataConnection.on('close', () => {
alert('Data connection has been closed.');
});
}
Here there are a few things that are hapening
setupDataConnectionEventsfunction adds listners for the data, open and close events to the current data connection
dataevent listener displays incoming messages
openevent adds a message to themessageDiv, telling us that a connection has been established
closeevent alerts the user that the connection has been closed
Displaying Messages
function displayMessage(message) {
messagesDiv.innerHTML += `<p>${message}</p>`;
}
this function adds messages to the messagesDiv thus showing messages on the screen
API: TURN server management with powerful API. You can do things like Add/ Remove credentials via the API, Retrieve Per User / Credentials and User metrics via the API, Enable/ Disable credentials via the API, Retrive Usage data by date via the API.
Global Geo-Location targeting: Automatically directs traffic to the nearest servers, for lowest possible latency and highest quality performance. less than 50 ms latency anywhere around the world
Servers in 12 Regions of the world: Toronto, Miami, San Francisco, Amsterdam, London, Frankfurt, Bangalore, Singapore,Sydney, Seoul
Low Latency: less than 50 ms latency, anywhere across the world.
Cost-Effective: pay-as-you-go pricing with bandwidth and volume discounts available.
Easy Administration: Get usage logs, emails when accounts reach threshold limits, billing records and email and phone support.
Standards Compliant: Conforms to RFCs 5389, 5769, 5780, 5766, 6062, 6156, 5245, 5768, 6336, 6544, 5928 over UDP, TCP, TLS, and DTLS.
Multi‑Tenancy: Create multiple credentials and separate the usage by customer, or different apps. Get Usage logs, billing records and threshold alerts.
Enterprise Reliability: 99.999% Uptime with SLA.- Enterprise Scale: With no limit on concurrent traffic or total traffic. Metered TURN Servers provide Enterprise Scalability
5 GB/mo Free: Get 5 GB every month free TURN server usage with the Free Plan- Runs on port 80 and 443
- Support TURNS + SSL to allow connections through deep packet inspection firewalls.
- Support STUN
- Supports both TCP and UDP
Conclusion
Thus in this article we have learned how we can add a turn server to a peer js project.
SOCIAL SHARE CARD GENERATOR