Performance: WebSocket server and client
This concept affects the real-time communication speed and responsiveness between client and server, impacting interaction latency and network efficiency.
import { serve } from "https://deno.land/std/http/server.ts"; serve(async (req) => { if (req.headers.get("upgrade") !== "websocket") { return new Response("Expected websocket", { status: 400 }); } const { socket, response } = Deno.upgradeWebSocket(req); socket.onmessage = async (e) => { // Use async non-blocking processing await new Promise((r) => setTimeout(r, 0)); socket.send(`Echo: ${e.data}`); }; return response; });
import { serve } from "https://deno.land/std/http/server.ts"; serve(async (req) => { if (req.headers.get("upgrade") !== "websocket") { return new Response("Expected websocket", { status: 400 }); } // Accept websocket but handle messages inefficiently const { socket, response } = Deno.upgradeWebSocket(req); socket.onmessage = (e) => { // Process message with blocking synchronous code for (let i = 0; i < 1e7; i++) {} // heavy loop blocks event loop socket.send(`Echo: ${e.data}`); }; return response; });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous message handler | Minimal | 0 | Low | [X] Bad |
| Async non-blocking message handler | Minimal | 0 | Low | [OK] Good |
| Sending large data immediately | Minimal | 0 | Low | [X] Bad |
| Sending large data in chunks asynchronously | Minimal | 0 | Low | [OK] Good |
Deno.upgradeWebSocket(request) to upgrade HTTP requests to WebSocket connections.const { socket, response } = Deno.upgradeWebSocket(request);
socket.onmessage = (e) => {
socket.send(`Received: ${e.data}`);
};const { socket, response } = Deno.upgradeWebSocket(request);
socket.onmessage = (e) => {
socket.send(e.data.toUpperCase());
};
return response;Pass the test and this pattern moves unknown