为了更好地组织代码并提高可复用性,我们可以将WebSocket客户端封装成一个工具类。这样可以在多个地方方便地使用WebSocket客户端功能。以下是使用tio库实现的一个WebSocket客户端工具类。
- 添加依赖
确保项目中添加了tio的依赖。如果使用的是Maven,可以在pom.xml文件中添加以下依赖:
<dependencies>
<!-- 其他依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>tio-core</artifactId>
<version>2.1.10</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>tio-websocket</artifactId>
<version>2.1.10</version>
</dependency>
</dependencies>
- 创建WebSocket客户端工具类
创建一个工具类TioWebSocketClientUtil,用于管理WebSocket客户端的连接和消息发送。
import org.tio.client.AioClient;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.websocket.client.WsClientConfig;
import org.tio.websocket.client.intf.ClientWsAioListener;
import org.tio.websocket.common.WsPacket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
public class TioWebSocketClientUtil {
private static final String SERVER_URL = "ws://your-spring-boot-server-url/websocket-endpoint";
private static final int PORT = 8080; // 服务器端口
private static final CountDownLatch latch = new CountDownLatch(1);
private static AioClient aioClient;
public static void init() throws Exception {
WsClientConfig config = new WsClientConfig();
config.setHeartbeatTimeoutSeconds(60); // 心跳超时时间
ClientWsAioListener aioListener = new ClientWsAioListener() {
@Override
public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect, boolean isFromHeartbeat) throws Exception {
super.onAfterConnected(channelContext, isConnected, isReconnect, isFromHeartbeat);
System.out.println("WebSocket connection opened.");
latch.countDown();
}
@Override
public void onAfterClosed(ChannelContext channelContext, Throwable throwable, String s, String s1) throws Exception {
super.onAfterClosed(channelContext, throwable, s, s1);
System.out.println("WebSocket connection closed.");
}
@Override
public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
super.onAfterSent(channelContext, packet, isSentSuccess);
System.out.println("Message sent: " + packet);
}
@Override
public void onAfterReceivedBytes(ChannelContext channelContext, byte[] bytes, int len) throws Exception {
super.onAfterReceivedBytes(channelContext, bytes, len);
System.out.println("Received bytes: " + new String(bytes, StandardCharsets.UTF_8));
}
@Override
public void onAfterReceivedPacket(ChannelContext channelContext, Packet packet) throws Exception {
super.onAfterReceivedPacket(channelContext, packet);
if (packet instanceof WsPacket) {
WsPacket wsPacket = (WsPacket) packet;
System.out.println("Received message: " + wsPacket.getString());
}
}
};
aioClient = new AioClient(config, aioListener);
aioClient.start();
}
public static void connect() throws Exception {
aioClient.connect(SERVER_URL, "client", PORT, null, null, 5000);
latch.await(); // 等待连接成功
}
public static void sendMessage(String message) throws Exception {
WsPacket wsPacket = new WsPacket();
wsPacket.setString(message);
aioClient.send(wsPacket);
}
public static void close() throws Exception {
aioClient.stop();
}
public static void main(String[] args) throws Exception {
init();
connect();
// 发送消息
sendMessage("Hello, server!");
// 等待一段时间后关闭连接
Thread.sleep(10000);
close();
}
}
- 解释
TioWebSocketClientUtil 类:封装了WebSocket客户端的基本功能。
init 方法:初始化WebSocket客户端配置并启动客户端。
connect 方法:连接到WebSocket服务器。
sendMessage 方法:发送消息给服务器。
close 方法:关闭客户端连接。
main 方法:演示如何使用这个工具类。
- 使用工具类
在其他类中可以通过调用TioWebSocketClientUtil的方法来使用WebSocket客户端功能:
public class MainApp {
public static void main(String[] args) {
try {
TioWebSocketClientUtil.init();
TioWebSocketClientUtil.connect();
// 发送消息
TioWebSocketClientUtil.sendMessage("Hello, server!");
// 等待一段时间后关闭连接
Thread.sleep(10000);
TioWebSocketClientUtil.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过这种方式,可以将WebSocket客户端功能封装成一个工具类,方便在多个地方使用。这样不仅提高了代码的可复用性,也使得客户端的管理和维护更加方便。