Integrating WebSocket with Frameworks

1. Using WebSocket in React

Example: useWebSocket hook (React 18+)

import { useEffect, useRef, useState } from "react";
export function useWebSocket(url: string) {
  const ref = useRef<WebSocket | null>(null);
  const [state, setState] = useState<"connecting"|"open"|"closed">("connecting");
  useEffect(() => {
    const ws = new WebSocket(url);
    ref.current = ws;
    ws.addEventListener("open",  () => setState("open"));
    ws.addEventListener("close", () => setState("closed"));
    return () => ws.close(1000, "unmount");
  }, [url]);
  return { ws: ref.current, state };
}
PatternDetail
HookEncapsulate lifecycle
StrictMode safeCleanup on unmount
Context providerShare single WS app-wide
React Query / SWRCombine WS push with cache
SuspensePending initial snapshot

2. Using WebSocket in Vue.js

Example: Vue 3 composable

import { onMounted, onUnmounted, ref } from "vue";
export function useWs(url: string) {
  const state = ref<"connecting"|"open"|"closed">("connecting");
  let ws: WebSocket | null = null;
  onMounted(() => {
    ws = new WebSocket(url);
    ws.addEventListener("open",  () => state.value = "open");
    ws.addEventListener("close", () => state.value = "closed");
  });
  onUnmounted(() => ws?.close(1000, "unmount"));
  return { state };
}
PatternDetail
ComposableReusable WS logic
Pinia storeGlobal WS state
VueUseuseWebSocket built-in

3. Using WebSocket in Angular

Example: Angular 17+ service

import { Injectable } from "@angular/core";
import { webSocket, WebSocketSubject } from "rxjs/webSocket";
@Injectable({ providedIn: "root" })
export class WsService {
  private sock: WebSocketSubject<unknown> = webSocket("wss://api.example.com/ws");
  messages$ = this.sock.asObservable();
  send(msg: unknown) { this.sock.next(msg); }
}
ToolUse
RxJS webSocketObservable WS subject
SignalsReactivity (Angular 17+)
NgRxEffects dispatch on message

4. Using WebSocket in Node.js

LibraryStrength
wsStandard, low-level
uWebSockets.jsHighest perf (C++)
socket.ioRooms, ack, fallbacks
graphql-wsGraphQL subscriptions

5. Using WebSocket in Python

Example: websockets (3.12+ asyncio)

import asyncio, websockets

async def handler(ws):
    async for msg in ws:
        await ws.send(f"echo:{msg}")

async def main():
    async with websockets.serve(handler, "0.0.0.0", 8080):
        await asyncio.Future()

asyncio.run(main())
LibraryUse
websocketsasyncio standard
FastAPI WebSocketIntegrated with REST app
Django ChannelsDjango integration
aiohttpCombined HTTP/WS server

6. Using WebSocket in Go

Example: gorilla/websocket (Go 1.21+)

package main

import (
    "net/http"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool { return true },
}

func handle(w http.ResponseWriter, r *http.Request) {
    c, _ := upgrader.Upgrade(w, r, nil)
    defer c.Close()
    for {
        mt, msg, err := c.ReadMessage()
        if err != nil { return }
        c.WriteMessage(mt, msg)
    }
}

func main() {
    http.HandleFunc("/ws", handle)
    http.ListenAndServe(":8080", nil)
}
LibraryNotes
gorilla/websocketMost popular, mature
nhooyr.io/websocketModern context-aware
gobwas/wsLow-level, zero-alloc

7. Using WebSocket in Java

Example: Spring Boot (Java 21+)

@Configuration
@EnableWebSocket
public class WsConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry r) {
        r.addHandler(new EchoHandler(), "/ws").setAllowedOrigins("*");
    }
}

public class EchoHandler extends TextWebSocketHandler {
    @Override
    public void handleTextMessage(WebSocketSession s, TextMessage m) throws IOException {
        s.sendMessage(new TextMessage("echo:" + m.getPayload()));
    }
}
StackDetail
Jakarta WebSocket (JSR 356)Standard API
Spring WebSocketSTOMP support
Spring Reactive (Netty)Non-blocking
Vert.xPolyglot, async

8. Using WebSocket in Rust

CrateUse
tokio-tungsteniteAsync, on tokio
axum + tokio-tungsteniteWeb framework integration
actix-web-actorsActor-based
warpFilter-based ergonomics

9. Using WebSocket in Worker Threads

Use CaseDetail
Off-main-thread parsingJSON/protobuf in Worker
Shared connectionSharedWorker — one socket per origin across tabs
Audio/video processingPipe binary frames

Example: SharedWorker WS bridge

// shared-worker.js
const ws = new WebSocket("wss://api.example.com/ws");
const ports = new Set();
onconnect = (e) => {
  const port = e.ports[0]; ports.add(port);
  port.onmessage = (ev) => ws.send(ev.data);
};
ws.addEventListener("message", (e) => { for (const p of ports) p.postMessage(e.data); });

10. Using WebSocket in Service Workers

Warning: Service Workers are short-lived and cannot keep a long-lived WebSocket open. Use them only for push notifications + waking the page; place the WS in the page or SharedWorker.
PatternDetail
Push notificationBrowser Push API wakes SW
SW forwards to pageclients.matchAll() + postMessage
Page opens WSFor sustained sync