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.
In client-server communication, a WebSocket connection is made once and reused until either the server or the client terminates the connection.
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.
See also:
Comments
0 comments
Article is closed for comments.