Creating a simple chat application using HTML and WebSockets involves both client-side and server-side code. Below is an example of a basic real-time chat using HTML, JavaScript, and a Node.js WebSocket server.
Server: Node.js WebSocket Server
First, create a WebSocket server using the ws library.
Initialize npm project and install ws:
bash
npm init -y
npm install ws
Create server.js:
js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('Client connected');
ws.on('message', function incoming(message) {
console.log('received: %s', message);
// Broadcast the message to all clients except sender
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server running on ws://localhost:8080');
Run the server:
bash
node server.js
Client: HTML + JavaScript
Here is a simple client to connect and chat via WebSocket: