Creating a basic HTML chat application using WebSockets involves setting up both a client (HTML/JavaScript) and a server that supports WebSocket connections. Below is a simple example using plain HTML and JavaScript for the client, and Node.js with the ws library for the server.
1. Server: Node.js WebSocket Server
First, you need a WebSocket server. Here's a minimal example using Node.js and the ws package.
Install the ws package:
npm install ws
server.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 incoming message to all clients
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.send('Welcome to the WebSocket chat!');
});
console.log("WebSocket server started on ws://localhost:8080");
Run the server with:
node server.js
2. Client: Simple HTML + JavaScript Chat
Save the following HTML file and open it in a browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>WebSocket Chat</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#chat { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; }
#message { width: 80%; }
#sendBtn { width: 18%; }
.message { margin: 5px 0; }
.self { color: blue; }
.other { color: green; }
</style>
</head>
<body>
<h1>WebSocket Chat</h1>
<div id="chat"></div>
<input type="text" id="message" placeholder="Type your message..." />
<button id="sendBtn">Send</button>
<script>
const ws = new WebSocket('ws://localhost:8080');
const chat = document.getElementById('chat');
const messageInput = document.getElementById('message');
const sendBtn = document.getElementById('sendBtn');
ws.onopen = () => {
appendMessage('System: Connected to the server.', 'system');
};
ws.onmessage = (event) => {
appendMessage(`Other: ${event.data}`, 'other');
};
ws.onclose = () => {
appendMessage('System: Disconnected from the server.', 'system');
};
ws.onerror = (error) => {
appendMessage('System: Error occurred.', 'system');
console.error('WebSocket error:', error);
};
sendBtn.onclick = sendMessage;
messageInput.addEventListener('keypress', function (e) {
if (e.key === 'Enter') sendMessage();
});
function sendMessage() {
const msg = messageInput.value.trim();
if (msg === '') return;
ws.send(msg);
appendMessage(`You: ${msg}`, 'self');
messageInput.value = '';
}
function appendMessage(msg, type) {
const el = document.createElement('div');
el.textContent = msg;
el.className = 'message ' + type;
chat.appendChild(el);
chat.scrollTop = chat.scrollHeight;
}
</script>
</body>
</html>
How this works:
- The server listens on port 8080 for incoming WebSocket connections.
- When a client sends a message, the server broadcasts it to all other connected clients.
- The client connects to the WebSocket server, sends messages typed by the user, and displays messages received from other users.
- Messages from you appear in blue; messages from others appear in green.
- The system messages (like connection status) are shown without a special color style; you can customize as needed.
Notes:
- Run your Node.js server first (
node server.js).
- Open multiple browser tabs with the HTML file to simulate multiple users chatting.
- This example is for learning and testing. For production, consider additional features like user authentication, message timestamps, security (WSS/SSL), etc.
Let me know if you want me to help with any particular feature!