EventSource vs WebSocket: Choosing the Right Real‑Time API for ChatGPT

This article explains the technical differences between Server‑Sent Events (EventSource) and WebSocket, compares their advantages, disadvantages, and suitable scenarios, and shows why ChatGPT’s streaming API prefers EventSource for server‑push communication.

JavaEdge
JavaEdge
JavaEdge
EventSource vs WebSocket: Choosing the Right Real‑Time API for ChatGPT

Introduction

ChatGPT official API only accepts a POST request. The response is not a conventional JSON payload but an EventStream, which follows the Server‑Sent Events (SSE) format returned by the browser EventSource interface.

EventSource (SSE) Overview

The EventSource API opens a persistent HTTP connection to a server that continuously streams data with MIME type text/event-stream. The connection stays open until the client calls EventSource.close(). Browsers automatically retry the connection if it drops.

EventSource vs WebSocket

EventSource

Simple to use : create new EventSource(url) and listen to message and error events.

One‑way server push : suitable for scenarios where the server only needs to push updates.

Automatic reconnection : the browser re‑establishes the connection with exponential back‑off.

Works with existing HTTP infrastructure : proxies, firewalls, and load balancers treat it as ordinary HTTP traffic.

Limitations

Unidirectional – client cannot send data over the same channel.

No binary frames or custom protocol features.

Higher overhead for high‑frequency or large‑payload streams compared with WebSocket.

Typical use cases

Real‑time dashboards (stock quotes, news feeds).

Lightweight notification systems.

Resource‑constrained environments where a full WebSocket stack is unnecessary.

WebSocket

Bidirectional communication : both client and server can send messages at any time.

Low latency and binary support : suitable for chat, gaming, or telemetry.

Rich protocol features : custom frames, sub‑protocol negotiation.

Limitations

Requires explicit handshake and server‑side implementation.

More complex client code (open, close, error handling, ping/pong).

May be blocked by older browsers or restrictive network policies.

Why ChatGPT Uses EventSource

ChatGPT’s streaming responses are incremental text fragments generated by the model. Delivering them via SSE provides several advantages:

Server‑push only : the model produces output continuously; the client only needs to receive it.

Built‑in reconnection : if the network drops, the browser automatically resumes the stream, preserving conversation continuity.

Simplicity : a single line of JavaScript— new EventSource(url) —is enough to start receiving tokens, avoiding the extra handshake logic required by WebSocket.

Broad browser support : all modern desktop and mobile browsers implement SSE, while some legacy environments still lack reliable WebSocket support.

Internally, ChatGPT rewrites the original POST semantics into a GET‑style request that the EventSource object can handle, then streams the model’s output as text/event-stream events.

Basic Usage Example

// Create an EventSource pointing to the ChatGPT streaming endpoint
const es = new EventSource('https://api.openai.com/v1/chat/completions/stream');

// Listen for incoming tokens
es.addEventListener('message', (e) => {
  // Each event data is a JSON line containing a token or partial response
  const data = JSON.parse(e.data);
  console.log('Token:', data.choices[0].delta.content);
});

// Handle errors and automatic reconnection
es.addEventListener('error', (err) => {
  console.error('Stream error', err);
  // The browser will attempt to reconnect automatically
});

Key Points

EventSource works only with GET requests; the API internally adapts the POST semantics.

For truly bidirectional interactions (e.g., sending user edits while receiving a response), a WebSocket implementation would be required.

When high‑frequency binary data or low‑latency round‑trip is essential, WebSocket remains the preferred choice.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ChatGPTWebSocketreal-time communicationServer-Sent EventsEventSource
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.