Sure! I'll provide you with a simple web application that allows two users to establish a peer-to-peer (P2P) connection via WebRTC, enabling them to exchange "ping" messages and display latency statistics.
We'll use WebRTC for P2P communication and WebSockets for signaling (to exchange connection setup information). The application consists of:
- A signaling server using Node.js and WebSocket.
- An HTML page with embedded JavaScript for the client-side logic.
Overview
- Signaling Server: Facilitates the exchange of WebRTC offer and answer between the two peers.
- Client-side Application:
- Connects to the signaling server.
- Establishes a WebRTC data channel.
- Provides a button to "ping" the other peer.
- Displays latency statistics.
Step 1: Set Up the Signaling Server
Server Code (server.js)
We'll create a simple signaling server using Node.js and the ws WebSocket library.
// server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const peers = [];
wss.on('connection', function connection(ws) {
peers.push(ws);
console.log('A new peer connected.');
ws.on('message', function incoming(message) {
console.log('Received:', message);
// Broadcast the message to the other peer
peers.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('A peer disconnected.');
// Remove the peer from the list
const index = peers.indexOf(ws);
if (index > -1) {
peers.splice(index, 1);
}
});
});
Instructions to Run the Server
- Install Node.js if you haven't already. Download it from nodejs.org.
- Create a folder for your project and navigate to it in your terminal.
- Initialize npm:
npm init -y
- Install Dependencies:
npm install ws
- Save the
server.js file into this folder.
- Run the server:
node server.js
The server listens on port 8080.
Step 2: Create the Client Application
HTML File (index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebRTC Ping Test</title>
<style>
body {
font-family: Arial, sans-serif;
}
#log {
border: 1px solid #ccc;
padding: 10px;
height: 200px;
overflow-y: scroll;
background-color: #f9f9f9;
}
#pingButton {
padding: 10px 20px;
font-size: 16px;
}
#stats {
margin-top: 10px;
}
</style>
</head>
<body>
<h1>WebRTC Ping Test</h1>
<button id="pingButton" disabled>Ping Peer</button>
<div id="stats"></div>
<h2>Log</h2>
<div id="log"></div>
<script src="client.js"></script>
</body>
</html>
Client-Side JavaScript (client.js)
// client.js
const pingButton = document.getElementById('pingButton');
const log = document.getElementById('log');
const statsDiv = document.getElementById('stats');
let localConnection;
let dataChannel;
let startTime;
let pingCount = 0;
let totalLatency = 0;
// Connect to the signaling server
const signalingServer = new WebSocket('ws://localhost:8080');
signalingServer.onopen = () => {
logMessage('Connected to the signaling server.');
setupPeerConnection();
};
signalingServer.onmessage = async (message) => {
const data = JSON.parse(message.data);
if (data.answer) {
// Received answer from peer
await localConnection.setRemoteDescription(new RTCSessionDescription(data.answer));
logMessage('Received answer from peer.');
} else if (data.offer) {
// Received offer from peer
logMessage('Received offer from peer.');
await localConnection.setRemoteDescription(new RTCSessionDescription(data.offer));
const answer = await localConnection.createAnswer();
await localConnection.setLocalDescription(answer);
// Send answer back to peer
signalingServer.send(JSON.stringify({ answer: answer }));
logMessage('Sent answer to peer.');
} else if (data.candidate) {
// Received ICE candidate from peer
await localConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
logMessage('Added ICE candidate.');
}
};
function setupPeerConnection() {
const configuration = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
],
};
localConnection = new RTCPeerConnection(configuration);
// Setup data channel
dataChannel = localConnection.createDataChannel('pingChannel');
dataChannel.onopen = onDataChannelOpen;
dataChannel.onmessage = onDataChannelMessage;
localConnection.onicecandidate = ({ candidate }) => {
if (candidate) {
signalingServer.send(JSON.stringify({ candidate: candidate }));
logMessage('Sent ICE candidate.');
}
};
// If the remote peer creates a data channel
localConnection.ondatachannel = (event) => {
dataChannel = event.channel;
dataChannel.onopen = onDataChannelOpen;
dataChannel.onmessage = onDataChannelMessage;
};
// Create an offer to connect with peer
localConnection.createOffer()
.then(offer => localConnection.setLocalDescription(offer))
.then(() => {
// Send the offer to the other peer
signalingServer.send(JSON.stringify({ offer: localConnection.localDescription }));
logMessage('Sent offer to peer.');
});
}
function onDataChannelOpen() {
logMessage('Data channel is open and ready.');
pingButton.disabled = false;
}
function onDataChannelMessage(event) {
const data = event.data;
if (data === 'ping') {
dataChannel.send('pong');
logMessage('Received ping and sent pong.');
} else if (data.startsWith('pong')) {
const latency = performance.now() - startTime;
pingCount++;
totalLatency += latency;
const averageLatency = (totalLatency / pingCount).toFixed(2);
statsDiv.innerText = `Latest Ping: ${latency.toFixed(2)} ms\nAverage Ping: ${averageLatency} ms`;
logMessage(`Received pong. Latency: ${latency.toFixed(2)} ms`);
}
}
pingButton.onclick = () => {
startTime = performance.now();
dataChannel.send('ping');
logMessage('Sent ping.');
};
function logMessage(message) {
const time = new Date().toLocaleTimeString();
log.innerHTML += `[${time}] ${message}<br>`;
log.scrollTop = log.scrollHeight;
}
Instructions to Run the Client Application
-
Save the index.html and client.js files in the same folder.
-
Serve the HTML file using a local web server. WebRTC and WebSockets require the page to be served over HTTP or HTTPS.
You can use a simple Python HTTP server:
Alternatively, you can use Node.js:
-
Open the application in the browser:
- Visit
http://localhost:8000 in your web browser.
- Note: Open the application in two separate browser windows or on two different devices.
Usage Instructions
- Ensure the signaling server is running:
node server.js
- Ensure the client application is served over HTTP as described above.
- Open the application in two different browsers or devices.
- Establish Connection:
- The clients will automatically attempt to connect via WebRTC upon loading.
- Check the log to see the connection status.
- Ping the Peer:
- Once the data channel is open, the "Ping Peer" button will be enabled.
- Click "Ping Peer" to send a ping message.
- The peer will automatically respond with a pong.
- Latency statistics will be displayed.
Explanation of How It Works
-
Signaling Server:
- Acts as a relay to exchange WebRTC offer/answer and ICE candidates.
- Keeps track of connected peers and forwards messages accordingly.
-
Client Application:
- WebSocket Connection: Establishes a connection with the signaling server for signaling.
- RTCPeerConnection: Creates a WebRTC peer connection.
- Data Channel: Sets up a data channel named
'pingChannel' for sending ping/pong messages.
- Offer/Answer Exchange: Uses the signaling server to exchange offers and answers.
- ICE Candidates: Exchanged via the signaling server to establish the best possible connection path.
- Ping Mechanism:
- When you click "Ping Peer," a
'ping' message is sent over the data channel.
- The peer listens for
'ping' messages and responds with 'pong'.
- Latency is calculated based on the time taken to receive
'pong' after 'ping' is sent.
-
Logging and Statistics:
- Logs important events to the on-page log for debugging and information.
- Displays the latest and average latency.
Additional Notes
-
Security Considerations:
- This example uses unsecured WebSocket (
ws://) and serves the page over HTTP. For a production environment, consider using secure WebSockets (wss://) and serving over HTTPS.
- WebRTC can expose IP addresses. In this example, we use Google's public STUN server. In a production environment, configure your own STUN/TURN servers.
-
Browser Compatibility:
- Ensure that you are using a modern browser that supports WebRTC (e.g., Chrome, Firefox, Edge).
-
Testing:
- For testing across the internet, ensure that your signaling server is accessible publicly.
- If testing locally, both clients should be on the same network, or you should configure NAT/firewall settings accordingly.
Troubleshooting
Conclusion
This simple application demonstrates how to establish a peer-to-peer connection between two browsers using WebRTC, allowing users to send ping messages and measure latency. The combination of WebRTC for direct communication and WebSockets for signaling provides a solid foundation for real-time, peer-to-peer web applications.
Feel free to enhance and customize the application further, such as adding more statistics, improving the UI, or implementing additional features.