learn2kode.in

HTML WebSocket API

WebSockets provide a way to open an interactive, two-way communication session between the browser and a server. Unlike traditional HTTP requests, WebSockets stay open, allowing data to move instantly in both directions. This makes them ideal for real-time applications such as chat apps, live notifications, stock updates, or multiplayer games.

What is WebSocket?

A WebSocket is a communication protocol that creates a persistent connection between a client and a server. Once the connection is established, both sides can send and receive data without new requests.

Why WebSockets Are Used

WebSocket URL Format

WebSocket connections use special protocols:

Protocol Description
ws:// Standard WebSocket connection
wss:// Secure WebSocket (encrypted like HTTPS)

Example

ws://example.com/socket
wss://secure-site.com/realtime

Basic WebSocket Example

<!DOCTYPE html>
<html>
<body>

<h2>WebSocket Example</h2>

<script>
  // Create a WebSocket connection
  let socket = new WebSocket("wss://echo.websocket.org");

  // When connection opens
  socket.onopen = function() {
    console.log("Connected to server");
    socket.send("Hello from Browser!");
  };

  // When a message is received
  socket.onmessage = function(event) {
    console.log("Message from server:", event.data);
  };

  // When connection closes
  socket.onclose = function() {
    console.log("Connection closed");
  };

  // If error occurs
  socket.onerror = function(error) {
    console.log("Error:", error);
  };
</script>

</body>
</html>

WebSocket Events

Event Trigger Description
onopen When connection starts Used to send initial data
onmessage When server sends data Receives real-time updates
onclose When connection ends Used for cleanup
onerror When an issue occurs Handles connection errors

WebSocket Methods

Method Purpose
send() Sends data to server
close() Closes the connection

Advantages of WebSockets

Limitations