Websockets
Chapter 21: WebSocket Connections
Section titled “Chapter 21: WebSocket Connections”Overview
Section titled “Overview”WebSockets provide persistent connections for real-time blockchain updates.
21.1 Why WebSockets?
Section titled “21.1 Why WebSockets?”| Feature | HTTP | WebSocket |
|---|---|---|
| Connection | Request-Response | Persistent |
| Latency | Higher | Lower |
| Real-time | Polling needed | Push-based |
| Use case | Queries | Live data |
21.2 Ethereum WebSocket
Section titled “21.2 Ethereum WebSocket”Connect
Section titled “Connect”const ws = new WebSocket('ws://localhost:8546');Subscribe to New Blocks
Section titled “Subscribe to New Blocks”ws.onopen = () => { ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'eth_subscribe', params: ['newHeads'], id: 1 }));};
ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log('New block:', data.params.result);};Subscribe to Pending Transactions
Section titled “Subscribe to Pending Transactions”ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'eth_subscribe', params: ['newPendingTransactions'], id: 2}));21.3 WebSocket Flags
Section titled “21.3 WebSocket Flags”geth \ --ws \ --ws.addr 0.0.0.0 \ --ws.port 8546 \ --ws.api eth,net,web3 \ --ws.origins "*" \ --ws.ratelimit 500Summary
Section titled “Summary”- WebSockets enable real-time updates
- Subscribe to new blocks, pending transactions
- Lower latency than HTTP polling
Last Updated: 2026-02-20