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 };
}
| Pattern | Detail |
|---|---|
| Hook | Encapsulate lifecycle |
| StrictMode safe | Cleanup on unmount |
| Context provider | Share single WS app-wide |
| React Query / SWR | Combine WS push with cache |
| Suspense | Pending 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 };
}
| Pattern | Detail |
|---|---|
| Composable | Reusable WS logic |
| Pinia store | Global WS state |
| VueUse | useWebSocket 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); }
}
| Tool | Use |
|---|---|
RxJS webSocket | Observable WS subject |
| Signals | Reactivity (Angular 17+) |
| NgRx | Effects dispatch on message |
4. Using WebSocket in Node.js
| Library | Strength |
|---|---|
ws | Standard, low-level |
uWebSockets.js | Highest perf (C++) |
socket.io | Rooms, ack, fallbacks |
graphql-ws | GraphQL 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())
| Library | Use |
|---|---|
websockets | asyncio standard |
FastAPI WebSocket | Integrated with REST app |
| Django Channels | Django integration |
| aiohttp | Combined 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)
}
| Library | Notes |
|---|---|
| gorilla/websocket | Most popular, mature |
| nhooyr.io/websocket | Modern context-aware |
| gobwas/ws | Low-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()));
}
}
| Stack | Detail |
|---|---|
| Jakarta WebSocket (JSR 356) | Standard API |
| Spring WebSocket | STOMP support |
| Spring Reactive (Netty) | Non-blocking |
| Vert.x | Polyglot, async |
8. Using WebSocket in Rust
| Crate | Use |
|---|---|
tokio-tungstenite | Async, on tokio |
axum + tokio-tungstenite | Web framework integration |
actix-web-actors | Actor-based |
warp | Filter-based ergonomics |
9. Using WebSocket in Worker Threads
| Use Case | Detail |
|---|---|
| Off-main-thread parsing | JSON/protobuf in Worker |
| Shared connection | SharedWorker — one socket per origin across tabs |
| Audio/video processing | Pipe 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.
| Pattern | Detail |
|---|---|
| Push notification | Browser Push API wakes SW |
| SW forwards to page | clients.matchAll() + postMessage |
| Page opens WS | For sustained sync |