socket-rtc
Version:
SocketRTC is a library that combines WebRTC and WebSocket to facilitate peer-to-peer communication. It allows for real-time communication between browsers and Node.js environments using WebRTC for direct peer-to-peer connections and WebSocket for signalin
109 lines (95 loc) • 3.42 kB
HTML
<!-- index.html -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SocketRTC Client</title>
<style>
#chat {
width: 100%;
max-width: 600px;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
height: 400px;
overflow-y: scroll;
}
.message {
padding: 5px;
margin: 5px 0;
}
.received {
text-align: left;
background-color: #c7e1ff;
}
</style>
</head>
<body>
<h1>SocketRTC Client</h1>
<div class="main">
<!-- <button id="connect" >Connet</button>
<button id="disconnect">Disconnect</button> -->
<input id="message" type="text" class="message" placeholder="Enter message" />
<button id="sendButton">Send</button>
<div id="chat"></div>
</div>
<script type="module">
const script = document.createElement('script');
const protocol = window.location.protocol;
const host = window.location.hostname;
const port = '8001';
const url = `${protocol}//${host}:${port}`;
script.src = `${url}/socketrtc.js`;
document.head.appendChild(script);
let rtc = null;
let id;
let chat = document.getElementById('chat');
script.onload = () => {
id = 'user' + Math.floor(Math.random() * 1000);
console.log(id)
rtc = new SocketRTC({ url }, id);
rtc.on('connect', onConnect);
rtc.on('disconnect', onDisconnect);
rtc.on('message', onMessageRecieved);
rtc.on('error', onError);
const sendButton = document.getElementById('sendButton');
sendButton.addEventListener('click', onSend);
};
function onSend() {
const message = document.getElementsByClassName('message')[0].value;
rtc.send(JSON.stringify({ sender: id, message }));
displayMessage('You', message);
// rtc.emit('message', message)
}
function onConnect() {
console.log('connected')
}
// Called when the client successfully disconnects from the server
function onDisconnect() {
console.log('disconnected')
}
// Called when the client receives a message
function onMessageRecieved(data) {
// console.log(message)
const { sender, message } = JSON.parse(data);
// Display the message if it's from another peer
if(message && sender !== id)
displayMessage(sender, message)
}
// Called when an error occurs in the client
function onError(err) {
console.error(err)
}
// Displays a message in the chat area of the UI
function displayMessage(sender, message) {
let messageElement = document.createElement('div');
messageElement.classList.add('message', 'received');
messageElement.innerHTML = `<strong>${sender}:</strong> ${message}`;
chat.appendChild(messageElement);
// Ensure the latest message is in view
chat.scrollTop = chat.scrollHeight;
}
</script>
</body>
</html>