Exth.Transport.Websocket (Exth v0.4.2)
View SourceWebSocket transport implementation for JSON-RPC requests using Fresh.
Implements the Exth.Transport.Transportable
protocol for making WebSocket
connections to JSON-RPC endpoints. Uses Fresh as the WebSocket client library.
Features
- Full-duplex communication
- Automatic connection management
- Asynchronous message handling
- Support for both ws:// and wss:// protocols
- Configurable dispatch callbacks
- Connection state management
Usage
transport = Transportable.new(
%Exth.Transport.Websocket{},
rpc_url: "wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID",
dispatch_callback: fn response -> handle_response(response) end
)
{:ok, response} = Transportable.call(transport, request)
Configuration
Required options:
:rpc_url
- The WebSocket endpoint URL (must start with ws:// or wss://):dispatch_callback
- Function to handle incoming messages (arity 1)
Message Flow
- Transport is initialized with a dispatch callback
- WebSocket connection is established
- Outgoing messages are sent through
call/2
- Incoming messages are handled by the dispatch callback
- Connection is maintained for subsequent requests
Error Handling
The transport handles several error cases:
- Invalid URL format
- Missing required options
- Connection failures
- Message dispatch errors
Best Practices
- Use wss:// for production environments
- Implement proper error handling in dispatch callbacks
- Monitor connection health
- Handle reconnection scenarios
- Clean up resources when done
See Exth.Transport.Transportable
for protocol details.