Creating a peer-to-peer (P2P) chat application where users can connect and send messages across different devices involves several steps. This requires using WebRTC (Web Real-Time Communication) for establishing P2P connections and a signaling server to facilitate the initial connection setup. Below is a simplified example of how you might structure this using HTML, JavaScript, and a basic signaling server.
Step 1: Set Up the Signaling Server
For simplicity, we'll use a Node.js server with Socket.IO for signaling. This server will help clients discover and connect to each other.
Install Dependencies:
npm init
npm install express socket.io
Server Code (server.js):
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
let users = {};
io.on('connection', (socket) => {
console.log('User connected');
socket.on('join', (username) => {
users[username] = socket.id;
console.log(`${username} joined`);
});
socket.on('connectTo', (username) => {
if (users[username]) {
const targetSocketId = users[username];
io.to(targetSocketId).emit('connectionRequest', socket.id);
}
});
socket.on('acceptConnection', (targetSocketId) => {
io.to(targetSocketId).emit('connectionEstablished', socket.id);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
http.listen(3000, () => {
console.log('Server listening on port 3000');
});
Step 2: Create the Client-Side HTML and JavaScript
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>P2P Chat</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h2>Peer-to-Peer Chat</h2>
<input id="username" placeholder="Enter your username" type="text"/>
<button onclick="join()">Join</button>
<input id="connectTo" placeholder="Enter username to connect to" type="text"/>
<button onclick="connectTo()">Connect</button>
<input id="message" placeholder="Type a message" type="text"/>
<button onclick="sendMessage()">Send</button>
<div id="chatLog"></div>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
let socket = io();
let peerConnection;
let dataChannel;
// Set up peer connection and data channel
function createPeerConnection() {
peerConnection = new RTCPeerConnection({
iceServers: [
{
urls: 'stun:stun.l.google.com:19302',
},
],
});
dataChannel = peerConnection.createDataChannel('myDataChannel');
dataChannel.onmessage = (event) => {
document.getElementById('chatLog').innerHTML += `<p>Received: ${event.data}</p>`;
};
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
// Send ICE candidate to the other peer
socket.emit('iceCandidate', event.candidate);
}
};
}
// Handle connection establishment
socket.on('connectionEstablished', (targetSocketId) => {
createPeerConnection();
peerConnection.createOffer().then((offer) => {
return peerConnection.setLocalDescription(offer);
}).then(() => {
socket.emit('offer', peerConnection.localDescription);
});
});
// Handle offer from other peer
socket.on('offer', (offer) => {
createPeerConnection();
peerConnection.setRemoteDescription(offer);
peerConnection.createAnswer().then((answer) => {
return peerConnection.setLocalDescription(answer);
}).then(() => {
socket.emit('answer', peerConnection.localDescription);
});
});
// Handle answer from other peer
socket.on('answer', (answer) => {
peerConnection.setRemoteDescription(answer);
});
// Handle ICE candidate from other peer
socket.on('iceCandidate', (candidate) => {
peerConnection.addIceCandidate(candidate);
});
// Send message over data channel
function sendMessage() {
const message = document.getElementById('message').value;
dataChannel.send(message);
document.getElementById('chatLog').innerHTML += `<p>Sent: ${message}</p>`;
document.getElementById('message').value = '';
}
// Join and connect functions
function join() {
const username = document.getElementById('username').value;
socket.emit('join', username);
}
function connectTo() {
const username = document.getElementById('connectTo').value;
socket.emit('connectTo', username);
}
Step 3: Serve the HTML File
Modify your server to serve the index.html file:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
Step 4: Run the Application
- Start the server by running
node server.js.
- Open two browser tabs and navigate to
http://localhost:3000.
- In each tab, enter a username and click "Join".
- In one tab, enter the other user's username in the "Connect to" field and click "Connect".
- Once connected, you can send messages between the two tabs.
This example provides a basic framework for establishing a P2P connection and sending messages. However, for production use, you would need to handle more complex scenarios, such as handling multiple connections, managing ICE candidates, and ensuring compatibility across different browsers and networks.