EventSource vs. wrapped WebSocket with HTML5 Server-Side Event

The EventSource API and WebSocket are both HTML5 technologies for real-time communication between client and server. However, they serve different purposes and have distinct characteristics. EventSource provides server-sent events (SSE) for one-way communication from server to client, while WebSocket enables full-duplex communication in both directions.

EventSource (Server-Sent Events)

EventSource is a simpler, lightweight solution for receiving real-time updates from the server. It establishes a persistent HTTP connection and listens for server-pushed data in a specific text format.

Key Characteristics

  • One-way communication − Client can only receive data from the server
  • Text/event-stream format − Uses a standardized plain text format
  • Automatic reconnection − Automatically reconnects if the connection is lost
  • Built-in event handling − Fires predefined and custom events
  • HTTP-based − Works through firewalls and proxies easily

Syntax

Following is the basic syntax for creating an EventSource connection −

var eventSource = new EventSource('server-endpoint.php');
eventSource.onmessage = function(event) {
    console.log('Data received: ' + event.data);
};

Example − EventSource Implementation

<!DOCTYPE html>
<html>
<head>
   <title>EventSource Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Live Updates with EventSource</h2>
   Connecting...
   
   <button onclick="closeConnection()">Close Connection</button>

   <script>
      var eventSource;
      var messagesDiv = document.getElementById('messages');
      var statusDiv = document.getElementById('status');

      // Simulate EventSource connection
      function startEventSource() {
         statusDiv.textContent = 'Connected to server';
         
         // Simulate receiving messages every 2 seconds
         var messageCount = 1;
         var interval = setInterval(function() {
            var message = 'Server update #' + messageCount + ' at ' + new Date().toLocaleTimeString();
            messagesDiv.innerHTML += '<p>' + message + '</p>';
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
            messageCount++;
            
            if (messageCount > 5) {
               clearInterval(interval);
               statusDiv.textContent = 'Connection ended (demo)';
            }
         }, 2000);
      }

      function closeConnection() {
         statusDiv.textContent = 'Connection closed';
         messagesDiv.innerHTML += '<p><em>Connection manually closed</em></p>';
      }

      // Start the demo
      startEventSource();
   </script>
</body>
</html>

The output demonstrates real-time server updates received through EventSource −

Live Updates with EventSource
Connected to server
Server update #1 at 10:30:15
Server update #2 at 10:30:17
Server update #3 at 10:30:19
[Close Connection]

WebSocket

WebSocket provides full-duplex communication, allowing both client and server to send data at any time. It uses its own protocol (ws:// or wss://) and is ideal for applications requiring fast, bidirectional communication.

Key Characteristics

  • Two-way communication − Both client and server can send data
  • Binary and text support − Can transmit various data formats
  • Low latency − Minimal protocol overhead after connection
  • Custom protocol − Uses WebSocket protocol, not HTTP
  • Manual reconnection − Requires custom reconnection logic

Syntax

Following is the basic syntax for creating a WebSocket connection −

var socket = new WebSocket('ws://localhost:8080');
socket.onmessage = function(event) {
    console.log('Received: ' + event.data);
};
socket.send('Hello Server');

Example − WebSocket Implementation

<!DOCTYPE html>
<html>
<head>
   <title>WebSocket Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Two-Way Communication with WebSocket</h2>
   Ready to connect
   
   <input type="text" id="messageInput" placeholder="Type a message..." style="width: 200px;">
   <button onclick="sendMessage()">Send</button>
   <button onclick="connectWebSocket()">Connect</button>

   <script>
      var socket;
      var chatDiv = document.getElementById('chat');
      var statusDiv = document.getElementById('status');
      var messageInput = document.getElementById('messageInput');

      function connectWebSocket() {
         statusDiv.textContent = 'Simulating WebSocket connection...';
         chatDiv.innerHTML += '<p><em>Connected to WebSocket server</em></p>';
         
         // Simulate server sending welcome message
         setTimeout(function() {
            chatDiv.innerHTML += '<p><strong>Server:</strong> Welcome! You are now connected.</p>';
            chatDiv.scrollTop = chatDiv.scrollHeight;
         }, 1000);
      }

      function sendMessage() {
         var message = messageInput.value.trim();
         if (message) {
            // Display sent message
            chatDiv.innerHTML += '<p><strong>You:</strong> ' + message + '</p>';
            
            // Simulate server response
            setTimeout(function() {
               chatDiv.innerHTML += '<p><strong>Server:</strong> Echo: ' + message + '</p>';
               chatDiv.scrollTop = chatDiv.scrollHeight;
            }, 500);
            
            messageInput.value = '';
         }
      }

      // Allow Enter key to send message
      messageInput.addEventListener('keypress', function(e) {
         if (e.key === 'Enter') {
            sendMessage();
         }
      });
   </script>
</body>
</html>

The output shows bidirectional communication where both client and server can send messages −

Two-Way Communication with WebSocket
Connected to WebSocket server
Server: Welcome! You are now connected.
You: Hello server
Server: Echo: Hello server
[Type a message...] [Send] [Connect]
EventSource vs WebSocket EventSource (SSE) ? One-way (server ? client) ? HTTP-based connection ? Auto-reconnection ? Text/event-stream format ? Firewall-friendly ? Live feeds, notifications Use: Server push only WebSocket ? Two-way (client ? server) ? WebSocket protocol ? Manual reconnection ? Binary + text support ? Low latency ? Real-time chat, gaming Use: Fast bidirectional

Comparison

Following table highlights the key differences between EventSource and WebSocket −

Feature EventSource (SSE) WebSocket
Communication One-way (server to client) Two-way (bidirectional)
Protocol HTTP/HTTPS WebSocket (ws://wss://)
Data Format Text/event-stream only Text and binary data
Reconnection Automatic Manual implementation required
Firewall/Proxy Works through most firewalls May be blocked by some firewalls
Complexity Simple to implement More complex, requires server support
Browser Support All modern browsers All modern browsers

Common Use Cases

EventSource is Ideal For

  • Live feeds − News updates, social media feeds
  • Live scores − Sports scores, election results
  • Stock market updates − Real-time stock prices
  • Notifications − System alerts, user notifications
  • Progress updates − File uploads, long-running processes

WebSocket is Ideal For

  • Real-time chat applications − Instant messaging, customer support
  • Online gaming − Multiplayer games requiring fast updates
  • Collaborative editing − Google Docs-style applications
  • Trading platforms − High-frequency trading applications
  • Video conferencing − Real-time audio/video streaming

Security Considerations

Both technologies have different security models. EventSource uses standard HTTP authentication and follows the same-origin policy by default, making it more straightforward to secure. WebSocket has its own security considerations, including the need for proper origin validation and custom authentication mechanisms since it doesn't automatically inherit HTTP session cookies.

Conclusion

Choose EventSource when you need simple, one-way communication from server to client with automatic reconnection. Choose WebSocket when you need fast, bidirectional communication between client and server. EventSource is simpler to implement and more firewall-friendly, while WebSocket offers greater flexibility and lower latency for real-time applications.

Updated on: 2026-03-16T21:38:53+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements