search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Set up a WebSocket server (Node.js ws)
Connect from HTML5 with the WebSocket API
Handle disconnections and reconnection gracefully
Add basic UX polish (no frameworks required)
Home 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)

Dec 28, 2025 am 03:00 AM

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.

How to Build a Real-Time Chat Application with HTML5 WebSockets? (Tutorial)

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) =&gt; {<br>  console.log('Client connected');<br>  ws.send(JSON.stringify({ type: 'welcome', message: 'Connected to chat!' }));<br><br>  ws.on('message', (data) =&gt; {<br>    try {<br>      const msg = JSON.parse(data);<br>      // Broadcast to all clients except sender<br>      wss.clients.forEach(client =&gt; {<br>        if (client !== ws &amp;&amp; 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 = () =&gt; {<br>  console.log('Connected to chat server');<br>};<br><br>socket.onmessage = (event) =&gt; {<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) =&gt; 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)