Web Front-end
H5 Tutorial
How to Build a Real-Time Chat Application with HTML5 WebSockets? (Tutorial)
How to Build a Real-Time Chat Application with HTML5 WebSockets? (Tutorial)
WebSockets enable instant, bidirectional real-time messaging via persistent connections; set up a Node.js server with the ws library, connect from HTML5 using the native WebSocket API, handle disconnections with reconnection logic, and enhance UX with local storage, Enter-to-send, and visual feedback.

Use WebSockets for instant, bidirectional messaging—no polling, no delays. Unlike HTTP requests that end after each response, WebSockets keep a persistent connection open between browser and server, letting both sides send data anytime. That’s what makes real-time chat possible.
Set up a WebSocket server (Node.js ws)
You need a lightweight server that speaks WebSocket protocol. The ws library is simple and widely used.
- Install it: npm install ws
- Create server.js:
const WebSocket = require('ws');<br>const wss = new WebSocket.Server({ port: 8080 });<br><br>wss.on('connection', (ws) => {<br> console.log('Client connected');<br> ws.send(JSON.stringify({ type: 'welcome', message: 'Connected to chat!' }));<br><br> ws.on('message', (data) => {<br> try {<br> const msg = JSON.parse(data);<br> // Broadcast to all clients except sender<br> wss.clients.forEach(client => {<br> if (client !== ws && client.readyState === WebSocket.OPEN) {<br> client.send(JSON.stringify({ ...msg, timestamp: new Date().toISOString() }));<br> }<br> });<br> } catch (e) {<br> console.error('Invalid JSON:', e);<br> }<br> });<br>}); - Run with node server.js — your WebSocket server is now live on ws://localhost:8080.
Connect from HTML5 with the WebSocket API
The browser uses the native WebSocket constructor. No extra libraries needed.
- In your index.html, declare a global socket variable and connect:
const socket = new WebSocket('ws://localhost:8080');<br><br>socket.onopen = () => {<br> console.log('Connected to chat server');<br>};<br><br>socket.onmessage = (event) => {<br> const msg = JSON.parse(event.data);<br> const messages = document.getElementById('messages');<br> const p = document.createElement('p');<br> p.textContent = `[${new Date(msg.timestamp).toLocaleTimeString()}] ${msg.user}: ${msg.text}`;<br> messages.appendChild(p);<br> messages.scrollTop = messages.scrollHeight; // Auto-scroll<br>};<br><br>socket.onerror = (error) => console.error('WebSocket error:', error);- Add a form to send messages — call socket.send() with structured JSON like { "user": "Alice", "text": "Hi there!" }.
Handle disconnections and reconnection gracefully
Networks drop. Browsers suspend tabs. Don’t assume the socket stays open.
- Listen for onclose and show a status indicator (e.g., “Offline — reconnecting…”).
- Implement simple reconnection logic: delay, exponential backoff, and max retries.
- Before sending, check socket.readyState === WebSocket.OPEN. If not, queue or warn.
- On reconnect, optionally fetch recent chat history from a REST endpoint (since WebSockets don’t store messages).
Add basic UX polish (no frameworks required)
Real-time doesn’t mean barebones. A few tweaks improve usability right away.
- Prevent duplicate submissions: disable the send button while waiting for onmessage or use a loading spinner.
- Let users pick a name — store it in localStorage so it persists across page reloads.
- Press Enter to send: attach event.key === 'Enter' to your input field.
- Add visual feedback: change the send button color briefly on click, or show “typing…” when someone else is composing (requires extending the protocol with typing events).
The above is the detailed content of How to Build a Real-Time Chat Application with HTML5 WebSockets? (Tutorial). 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
20521
7
13634
4




