1. Introduction
1.绪论
AsyncHttpClient (AHC) is a library, based on Netty, created to easily execute asynchronous HTTP calls and communicate over the WebSocket protocol.
AsyncHttpClient(AHC)是一个基于Netty的库,它的创建是为了轻松地执行异步HTTP调用和通过WebSocket协议进行通信。
In this quick tutorial, we’ll see how we can start a WebSocket connection, send data and handle various control frames.
在这个快速教程中,我们将看到如何启动WebSocket连接、发送数据和处理各种控制框架。
2. Setup
2.设置
The latest version of the library can be found on Maven Central. We need be careful to use the dependency with the group id org.asynchttpclient and not the one with com.ning:
该库的最新版本可以在Maven中心找到。我们需要注意使用组名为org.asynchttpclient的依赖关系,而不是com.ning:的那个。
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.2.0</version>
</dependency>
3. WebSocket Client Configuration
3.WebSocket客户端配置
To create a WebSocket client, we first have to obtain an HTTP client as shown in this article and upgrade it to support the WebSocket protocol.
要创建一个WebSocket客户端,我们首先要获得一个HTTP客户端,如本文章所示,并将其升级以支持WebSocket协议。
The handling for the WebSocket protocol upgrade is done by the WebSocketUpgradeHandler class. This class implements the AsyncHandler interface and also provides us with a builder:
WebSocket协议升级的处理是由WebSocketUpgradeHandler类完成的。该类实现了AsyncHandler接口,还为我们提供了一个构建器。
WebSocketUpgradeHandler.Builder upgradeHandlerBuilder
= new WebSocketUpgradeHandler.Builder();
WebSocketUpgradeHandler wsHandler = upgradeHandlerBuilder
.addWebSocketListener(new WebSocketListener() {
@Override
public void onOpen(WebSocket websocket) {
// WebSocket connection opened
}
@Override
public void onClose(WebSocket websocket, int code, String reason) {
// WebSocket connection closed
}
@Override
public void onError(Throwable t) {
// WebSocket connection error
}
}).build();
For obtaining a WebSocket connection object we use the standard AsyncHttpClient to create an HTTP request with the preferred connection details, like headers, query parameters or timeouts:
为了获得一个WebSocket连接对象,我们使用标准的AsyncHttpClient来创建一个带有首选连接细节的HTTP请求,如头文件、查询参数或超时。
WebSocket webSocketClient = Dsl.asyncHttpClient()
.prepareGet("ws://localhost:5590/websocket")
.addHeader("header_name", "header_value")
.addQueryParam("key", "value")
.setRequestTimeout(5000)
.execute(wsHandler)
.get();
4. Sending Data
4.发送数据
Using the WebSocket object we can check whether the connection is successfully opened using the isOpen() method. Once we have an open connection we can send data frames with a string or binary payload using the sendTextFrame() and sendBinaryFrame() methods:
使用WebSocket对象我们可以使用isOpen()方法检查连接是否已成功打开。一旦我们有了一个开放的连接,我们可以使用sendTextFrame()和sendBinaryFrame()方法发送带有字符串或二进制有效载荷的数据帧。
if (webSocket.isOpen()) {
webSocket.sendTextFrame("test message");
webSocket.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'});
}
5. Handling Control Frames
5.处理控制帧
The WebSocket protocol supports three types of control frames: ping, pong, and close.
WebSocket协议支持三种类型的控制帧:ping、pong和close。
The ping and pong frame are mainly used to implement a “keep-alive” mechanism for the connection. We can send these frames using the sendPingFrame() and sendPongFrame() methods:
ping和pong框架主要用于实现连接的 “保持 “机制。我们可以使用sendPingFrame()和sendPongFrame()方法发送这些框架。
webSocket.sendPingFrame();
webSocket.sendPongFrame();
Closing the existing connection is done by sending a close frame using the sendCloseFrame() method, in which we can provide a status code and a reason for closing the connection in the form of a text:
关闭现有的连接是通过使用sendCloseFrame()方法发送一个关闭帧来完成的,在该方法中我们可以以文本的形式提供一个状态代码和一个关闭连接的理由。
webSocket.sendCloseFrame(404, "Forbidden");
6. Conclusion
6.结语
Having support for the WebSocket protocol, besides the fact that it provides an easy way to execute asynchronous HTTP requests, makes AHC a very powerful library.
对WebSocket协议的支持,除了为执行异步HTTP请求提供了一种简单的方法外,还使AHC成为一个非常强大的库。
The source code for the article is available over on GitHub.
该文章的源代码可在GitHub上获得。