Creating WebSocket Connections (Client-Side)
1. Creating Client Connection
| Signature | Description |
new WebSocket(url) | Open connection |
new WebSocket(url, protocol) | Single subprotocol |
new WebSocket(url, protocols[]) | Preferred-order list |
Example: Basic connect
const ws = new WebSocket("wss://api.example.com/ws");
ws.addEventListener("open", () => console.log("connected"));
2. Creating Secure Connection
| Requirement | Detail |
| Valid TLS cert | Browsers reject self-signed in prod |
| TLS 1.2+ | 1.3 preferred |
| SNI | Required for shared hosts |
| HSTS | Inherits from origin |
3. Specifying Subprotocols
Example: Subprotocol negotiation
const ws = new WebSocket("wss://x.example.com/ws", ["chat.v2", "chat.v1"]);
ws.addEventListener("open", () => console.log("active:", ws.protocol));
| Aspect | Detail |
| Order | Most preferred first |
| Negotiation | Server picks one (or none) |
| Failure | If none chosen, server should close |
4. Setting Connection URL
| Property | Value |
ws.url | Resolved URL (read-only) |
Note: The URL is fixed at construction; you cannot change it after.
5. Checking Connection State
Example: State check
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "ping" }));
| State | Numeric |
WebSocket.CONNECTING | 0 |
WebSocket.OPEN | 1 |
WebSocket.CLOSING | 2 |
WebSocket.CLOSED | 3 |
6. Setting Binary Type
| Value | Effect on incoming binary |
"blob" (default) | Delivered as Blob |
"arraybuffer" | Delivered as ArrayBuffer |
Example: ArrayBuffer mode
ws.binaryType = "arraybuffer";
ws.addEventListener("message", (e) => {
if (e.data instanceof ArrayBuffer) decode(new DataView(e.data));
});
7. Using WebSocket Properties
| Property | Type | Description |
url | string | Resolved URL |
readyState | number | Connection state |
bufferedAmount | number | Queued bytes not yet sent |
extensions | string | Negotiated extensions |
protocol | string | Negotiated subprotocol |
binaryType | string | "blob" / "arraybuffer" |
8. Feature Detection
Example: Detect support
if (typeof WebSocket === "undefined") {
showLegacyFallback();
}
| Check | Meaning |
"WebSocket" in window | API present |
WebSocket.CLOSING === 2 | Spec-compliant |
9. Handling Browser Compatibility
| Concern | Mitigation |
| Old browsers | Use Socket.IO / SockJS fallback |
| Safari deflate quirks | Disable permessage-deflate if issues |
| Mobile background | Reconnect on visibility change |
10. Using WebSocket in Workers
Example: WS inside Web Worker
// worker.js
const ws = new WebSocket("wss://api.example.com/ws");
ws.addEventListener("message", (e) => self.postMessage(e.data));
self.onmessage = (e) => ws.send(e.data);
| Context | Supported? |
| Dedicated Worker | Yes |
| Shared Worker | Yes |
| Service Worker | Limited Support (no persistent WS) |