This article applies to:
- Ethereum
- Polygon
- BNB Smart Chain
- Avalanche
- Fantom
- Harmony
Difference between HTTP and WebSocket protocols
HTTP is unidirectional while WebSocket is bidirectional.
In client-server communication, each HTTP request from the client establishes a new connection and gets closed on receiving a response from the server.
WebSockets provide a full-duplex communication channel over a single TCP connection, enabling real-time interaction with an Ethereum Virtual Machine (EVM) node. This is particularly useful for applications that require immediate updates, such as dApps, monitoring tools, and trading bots.
Proper use of WebSocket to connect to an EVM node
When using WebSocket to connect to an EVM node, the recommendation is to open a connection and send requests over the open connection instead of opening a new connection like with HTTP requests.
Reusing the same open connection with WebSocket prevents the EVM node connection pool from running out.
Incorrect usage example with web3.py:
def getLatestBlock():
web3 = Web3(Web3.WebsocketProvider('wss://ws-nd-123-456-789.p2pify.com/3c6e0b8a9c15224a8228b9a98ca1531'))
return web3.eth.blockNumber
getLatestBlock()
This example creates a new connection for each getLatestBlock request and keeps the connection open but never used again.
Correct usage example with web3.py:
web3 = Web3(Web3.WebsocketProvider('wss://ws-nd-123-456-789.p2pify.com/3c6e0b8a9c15224a8228b9a98ca1531'))
def getLatestBlock():
return web3.eth.blockNumber
getLatestBlock()
This example creates one connection and reuses it for each getLatestBlock request. Dealing with care with your WSS connections if fundamental given there is a limit of 250 connections to each endpoint URL. You can find more details on such limits here.
See also:
Comments
0 comments
Article is closed for comments.