Building a real-time chat application with HTML5 WebSockets.
设置基于Node.js和ws库的WebSocket服务器,监听8080端口并广播消息;2. 创建HTML前端界面,通过原生WebSocket API连接服务器;3. 实现消息发送与接收功能,支持多客户端实时通信;4. 启动服务并多窗口测试,确保消息同步。

Creating a real-time chat application using HTML5 WebSockets is a straightforward way to enable instant communication between users. WebSockets provide a persistent, two-way connection between the client and server, making them ideal for chat functionality.
Set Up the Backend WebSocket Server
You need a server that supports WebSocket connections. Node.js with the ws library is a popular choice.
- Install Node.js and initialize a project:
npm init -y - Install the ws package:
npm install ws - Create a server file (e.g., server.js)
Example server code:
<font size="-2">
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received:', message);
// Broadcast message to all connected clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
</font>
This starts a WebSocket server on port 8080 and broadcasts any received message to all connected clients.
Create the Frontend with HTML and JavaScript
The client interface uses the native WebSocket API in the browser.
- Create an index.html file
- Add input fields for messages and a display area
- Use JavaScript to connect to the WebSocket server
Example frontend code:
<font size="-2">
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Chat</title>
</head>
<body>
<h2>Chat Room</h2>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to server');
};
socket.onmessage = (event) => {
const messages = document.getElementById('messages');
const message = document.createElement('div');
message.textContent = event.data;
messages.appendChild(message);
};
function sendMessage() {
const input = document.getElementById('messageInput');
if (input.value) {
socket.send(input.value);
input.value = '';
}
}
// Allow sending message with Enter key
document.getElementById('messageInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
</script>
</body>
</html>
</font>
Run and Test the Application
Start the server and open the HTML page in multiple browser windows to simulate different users.
- Run the server:
node server.js - Open index.html in two or more browser tabs
- Type a message in one tab and press Send — it should appear in all tabs instantly
Ensure your firewall allows connections on port 8080, or adjust the port as needed.
Basically just connect the frontend to the backend using WebSockets, handle message sending and receiving, and broadcast to all clients. With minimal code, you have a working real-time chat app.
The above is the detailed content of Building a real-time chat application with HTML5 WebSockets.. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to use the template tag for dynamic content in HTML5? (Cloning nodes)
Mar 05, 2026 am 02:15 AM
The template tag itself does not render and must be manually cloned and inserted. Template is a lazy container of HTML5. The browser will parse it but completely skip rendering and script execution. If you write Hello directly, nothing will appear on the page - this is not a bug, it is the design. To make it "alive", you must use JavaScript to extract the content, clone it, and then hang it on the DOM. A common mistake is to directly obtain document.querySelector('template').content and then try to appendChild. The result is an error or no response: because the content is a Docu
How to make a phone number clickable in HTML5? (Tel link)
Mar 05, 2026 am 02:29 AM
The correct way to write it is href="tel: 8613812345678". All non-numeric characters need to be cleared (only and numbers are retained). Mainland China numbers must be prefixed with 86. Extension numbers use;ext= format, and target="_blank" is disabled.
How to disable autocomplete on input fields in HTML5? (Form attributes)
Mar 05, 2026 am 02:31 AM
Autocomplete="off" sometimes does not take effect because modern browsers (such as Chrome ≥ 80) actively ignore it to ensure the password manager experience; to be truly effective, it needs to be combined with strategies such as semantic values (such as new-password), avoiding sensitive names, and dynamically generated attributes.
How to create a progress bar for file uploads in HTML5? (Progress tag)
Mar 06, 2026 am 02:22 AM
Why can't the tag directly display the upload progress? It is a read-only visual component. It does not listen to network requests and is not automatically bound to the upload process of XMLHttpRequest or fetch. If you put it in and don't update the value manually, it will always stop at 0%. What really drives it is the event monitoring in the upload logic you write yourself. A common mistake is to only monitor onload (upload completed) but miss upload.onprogress. XMLHttpRequest (not fetch) must be used to obtain real-time upload progress, because fetch does not expose the max attribute of the event in the upload phase and must be set to the file size (file.size
How to create a tooltip using only HTML5? (Title attribute)
Mar 06, 2026 am 12:23 AM
The title attribute is not a tooltip component, but an accessibility prompt mechanism implemented by the browser. The behavior, style, and interaction are uncontrollable and are only suitable for simple scenarios such as pure information supplement.
How to center an image vertically in HTML5? (Layout techniques)
Mar 07, 2026 am 02:05 AM
Flexbox is the most stable for centered images. The key is to set display:flex and align-items:center in the parent container and specify the height; using place-items:center for Grid is more concise; absolute positioning requires top:50% with transform:translateY(-50%); vertical-align is invalid for block-level centering.
How to insert a copyright symbol in HTML5? (Character entities)
Mar 05, 2026 am 02:57 AM
© and © have the same effect. The former is a named entity and is easy to read, while the latter is a decimal digital entity and has more stable compatibility. It is necessary to avoid the problems of CSS hiding, JS unescapement and missing semantics.
How to create a simple offline web app with HTML5? (Application Cache)
Mar 06, 2026 am 02:16 AM
ApplicationCache has been completely abandoned and will be removed from Chrome 61, Firefox 72, and Safari 11.1. ServiceWorker must be used instead; the latter requires HTTPS, manual registration and cache control, and the path, scope, and life cycle must match exactly.





