Unlike request/response HTTP, a WebSocket keeps one connection open in both directions, letting a node push events as they happen — new blocks, pending transactions, contract event logs — instead of the client polling.
js
import WebSocket from "ws";
const ws = new WebSocket(process.env.WS_RPC_URL);
ws.on("open", () => {
ws.send(JSON.stringify({
jsonrpc: "2.0", id: 1, method: "eth_subscribe", params: ["newHeads"],
}));
});
ws.on("message", (data) => {
const msg = JSON.parse(data.toString());
if (msg.method === "eth_subscription") {
console.log("new block:", msg.params.result.number);
}
});WebSocket connections need reconnection logic: networks drop, nodes restart, and a production service must detect a closed socket and re-subscribe rather than silently going quiet.