chat_server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const port = 8989;
const server = http.createServer(express);
const wss = new WebSocket.Server({ server })
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
})
})
})
server.listen(port, function() {
console.log(`Server is listening on ${port}!`)
})
index.html
<center><h1>WS Chat App</h1></center>
<pre id="messages" style="height: 400px; overflow: scroll"></pre>
<input type="text" id="messageBox" placeholder="Type your message here" style="display: block; width: 100%; margin-bottom: 10px; padding: 10px;" onkeyup="validateInput(event)"/>
<button id="send" title="Send Message!" style="width: 100%; height: 30px;">Send Message</button>
<script>
(function() {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');
let ws;
function showMessage(message) {
if (message instanceof Blob) {
reader = new FileReader();
reader.onload = () => {
// console.log("Result: " + reader.result);
messages.textContent += `\n\n${reader.result}`;
};
reader.readAsText(message);
} else {
console.log("Result: " + message);
messages.textContent += `\n\n${message}`;
}
messages.scrollTop = messages.scrollHeight;
messageBox.value = "";
}
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('ws://localhost:8989');
ws.onopen = () => {
console.log('Connection opened!');
}
ws.onmessage = ({ data }) => showMessage(data);
ws.onclose = function() {
ws = null;
}
}
sendBtn.onclick = function() {
if (!ws) {
showMessage("No WebSocket connection :(");
return ;
}
ws.send(messageBox.value);
showMessage(messageBox.value);
}
messageBox.onkeyup = function() {
if(event.keyCode == 13) {
if (!ws) {
showMessage("No WebSocket connection :(");
return ;
}
ws.send(messageBox.value);
showMessage(messageBox.value);
}
}
init();
})();
</script>