Ethereum WebSocket接口实践
之前在学习Ethereum的infura API时候看到有WebSocket,但是翻了很久都没找到很完整的接口文档和实践文档。当时比较迷,没太在意,以为是区块链接口的性能还用不上WebSocket,HTTP完全支持没问题。
后面在更深入学习了jsonrpc协议之后,我突然悟道了可能不需要WebSocket的接口文档也能发起请求。
经过一些失败的尝试,基本摸清楚了这里面的弯弯道道。其实就是把Web3j源码翻看一下,基本也能猜个八九不离十。下面举个最简单的例子。
Web3j源码
我们找了获取网络版本的API:net_version
。下面是尝试找到的Web3j的源码内容:
public Request<?, NetVersion> netVersion() {
return new Request("net_version", Collections.emptyList(), this.web3jService, NetVersion.class);
}
这里我们看到 org.web3j.protocol.core.Request
构造方法,下面是内容:
public Request(String method, List<S> params, Web3jService web3jService, Class<T> type) {
this.method = method;
this.params = params;
this.id = nextId.getAndIncrement();
this.web3jService = web3jService;
this.responseType = type;
}
到这里,我们就基本了解了如何构造请求的初步逻辑,下面我们看一下WebSocket的如何发送请求信息的:
client.send("{\"jsonrpc\":\"2.0\",\"method\":\"net_version\",\"params\":[],\"id\":1333333}")
是不是有点熟悉,刚好跟 org.web3j.protocol.core.Request
属性对应。到这里相比大家是不是都差不多明白了。
再补充一个信息,就是 org.web3j.protocol.core.Request
的属性定义部分代码。
private static AtomicLong nextId = new AtomicLong(0L);
private String jsonrpc = "2.0";
private String method;
private List<S> params;
private long id;
private Web3jService web3jService;
private Class<T> responseType;
这里用到了之前分享过的 java.util.concurrent.atomic.AtomicLong
,用来作为全局的唯一ID非常合适。
WebSocket API实践
这里我用到了我自己封装的WebSocket的客户端 com.funtester.socket.WebSocketFunClient
,用的是 goerli
测试网络的WebSocket地址。话不多说,上代码:
static final String host = "wss://goerli.infura.io/ws/v3/apikey"
static void main(String[] args) {
def client = new WebSocketFunClient(host, "infura ethereum")
client.connect()
client.send("{\"jsonrpc\":\"2.0\",\"method\":\"eth_accounts\",\"params\":[],\"id\":1}")
client.send("{\"jsonrpc\":\"2.0\",\"method\":\"net_version\",\"params\":[],\"id\":1333333}")
}
控制台输出:
22:03:41.023 main infura ethereum 开始连接...
22:03:42.447 WebSocketConnectReadThread-20 infura ethereum 正在建立socket连接...
22:03:42.447 WebSocketConnectReadThread-20 握手信息key: Connection ,value: upgrade
22:03:42.447 WebSocketConnectReadThread-20 握手信息key: Date ,value: Tue, 07 Nov 2023 14:03:42 GMT
22:03:42.447 WebSocketConnectReadThread-20 握手信息key: Sec-WebSocket-Accept ,value: dia6CeCsPpnqTtBXZsLc58pxWmk=
22:03:42.448 WebSocketConnectReadThread-20 握手信息key: Upgrade ,value: websocket
22:03:44.028 main infura ethereum 连接成功!
22:03:44.299 WebSocketConnectReadThread-20 infura ethereum收到: {"jsonrpc":"2.0","id":1,"result":[]}
22:03:44.544 WebSocketConnectReadThread-20 infura ethereum收到: {"jsonrpc":"2.0","id":1333333,"result":"5"}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2019-11-17 成为自动化测试的7种技能
2019-11-17 自动化和手动测试,保持平衡!
2019-11-17 Groovy单元测试框架spock数据驱动Demo