codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🎨

HTML & CSS

38 / 59 topics
34HTML5 History API35HTML5 Web Workers36HTML5 Service Workers37HTML5 Fetch API38HTML5 WebSockets39HTML5 Geolocation API40HTML5 Device Orientation API41HTML5 Payment Request API42HTML5 Push Notifications
Tutorials/HTML & CSS/HTML5 WebSockets
🎨HTML & CSS

HTML5 WebSockets

Updated 2026-04-20
2 min read

HTML5 WebSockets

Introduction

WebSockets provide a full-duplex communication channel over a single, long-lived connection. This makes them ideal for real-time applications such as live chat, online games, and collaborative tools. Unlike HTTP requests, which are typically one-directional and require a new request for every update, WebSockets allow data to be sent back and forth between the client and server without the need for additional requests.

Setting Up a WebSocket Connection

To establish a WebSocket connection, you first need to create a WebSocket object in your JavaScript code. Here's how you can do it:

// Create a new WebSocket connection
const socket = new WebSocket('ws://example.com/socket');

// Event listener for when the connection is opened
socket.addEventListener('open', function (event) {
    console.log('Connected to the server');
    // Send an initial message to the server
    socket.send('Hello Server!');
});

// Event listener for incoming messages from the server
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

// Event listener for when the connection is closed
socket.addEventListener('close', function (event) {
    console.log('Connection closed');
});

// Error handling
socket.addEventListener('error', function (event) {
    console.error('WebSocket error observed:', event);
});

Explanation

  • new WebSocket(url): Initializes a new WebSocket connection to the specified URL.
  • open event: Triggered when the connection is successfully established.
  • message event: Triggered whenever a message is received from the server.
  • close event: Triggered when the connection is closed.
  • error event: Triggered if there's an error in the WebSocket connection.

Sending and Receiving Messages

Once the connection is established, you can send messages to the server using the send() method:

// Send a message to the server
socket.send('Hello Server!');

Messages received from the server are handled in the message event listener:

// Handle incoming messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

Best Practices

  • Use JSON for Data Exchange: For structured data, it's best to use JSON. This allows you to easily parse and manipulate the data on both the client and server sides.

    // Sending JSON data
    socket.send(JSON.stringify({ type: 'message', content: 'Hello Server!' }));
    
    // Receiving JSON data
    socket.addEventListener('message', function (event) {
        const data = JSON.parse(event.data);
        console.log(data.type, data.content);
    });
    
  • Handle Connection Errors: Always handle errors to ensure your application can gracefully recover from connection issues.

Server-Side Implementation

To use WebSockets on the server side, you need a WebSocket server library. Here's an example using Node.js with the ws library:

const WebSocket = require('ws');

// Create a new WebSocket server
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        // Broadcast to everyone else.
        wss.clients.forEach(function each(client) {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    ws.send('Welcome to the server!');
});

Explanation

  • WebSocket.Server: Initializes a new WebSocket server.
  • connection event: Triggered when a new client connects.
  • message event: Triggered when a message is received from a client.

Security Considerations

WebSockets can be vulnerable to various security issues, such as man-in-the-middle attacks and cross-site scripting (XSS). Here are some best practices:

  • Use Secure Connections: Always use wss:// (WebSocket Secure) instead of ws://. This encrypts the data being transmitted.

    const socket = new WebSocket('wss://example.com/socket');
    
  • Validate and Sanitize Inputs: Ensure that all incoming messages are validated and sanitized to prevent XSS attacks.

Conclusion

WebSockets provide a powerful way to enable real-time communication in web applications. By understanding how to establish, send, and receive messages using WebSockets, you can build interactive and responsive web applications. Always consider security best practices to protect your application from potential threats.


PreviousHTML5 Fetch APINext HTML5 Geolocation API

Recommended Gear

HTML5 Fetch APIHTML5 Geolocation API