跳转到内容

WebSocket 客户端

WebSocket 协议支持客户端与服务器之间的全双工通信,适用于实时聊天、在线游戏、股票行情推送、物联网设备控制等场景。Feat 提供了简洁的 WebSocketClient API 来实现 WebSocket 客户端功能。

以下示例展示 WebSocket 客户端的最基本用法:

import tech.smartboot.feat.core.client.WebSocketClient;
import tech.smartboot.feat.core.client.WebSocketListener;
import tech.smartboot.feat.core.client.WebSocketResponse;
public class WebSocketDemo {
public static void main(String[] args) {
// 1. 创建客户端实例
WebSocketClient client = new WebSocketClient("ws://localhost:8080/ws");
// 2. 建立连接
client.connect(new WebSocketListener() {
@Override
public void onOpen(WebSocketClient client, WebSocketResponse response) {
System.out.println("连接成功");
// 连接建立后发送消息
client.sendMessage("Hello, Feat!");
}
@Override
public void onMessage(WebSocketClient client, String message) {
System.out.println("收到消息: " + message);
}
@Override
public void onClose(WebSocketClient client, WebSocketResponse response, CloseReason reason) {
System.out.println("连接关闭: " + reason);
}
@Override
public void onError(WebSocketClient client, WebSocketResponse response, Throwable throwable) {
System.out.println("发生错误: " + throwable.getMessage());
}
});
}
}

核心步骤:

  1. 创建客户端 - 通过 URL 构造 WebSocketClient,支持 ws://wss:// 协议
  2. 实现监听器 - 实现 WebSocketListener 接口处理各类事件
  3. 建立连接 - 调用 connect() 方法发起连接

WebSocket 支持文本消息和二进制消息:

// 发送文本消息
client.sendMessage("Hello, World!");
// 发送二进制消息
byte[] binaryData = "Binary Data".getBytes(StandardCharsets.UTF_8);
client.sendBinary(binaryData);

通过 options() 方法获取配置对象,自定义连接参数:

WebSocketClient client = new WebSocketClient("wss://example.com/ws");
client.options()
.connectTimeout(5000) // 连接超时时间(毫秒)
.readBufferSize(8192) // 读缓冲区大小
.writeBufferSize(8192) // 写缓冲区大小
.debug(true) // 开启调试日志
.proxy("proxy.example.com", 8080, "user", "password"); // 代理配置
配置项类型默认值说明
connectTimeoutint30000连接超时时间(毫秒)
readBufferSizeint4096读缓冲区大小(字节)
writeBufferSizeint4096写缓冲区大小(字节)
debugbooleanfalse是否输出调试日志
proxyString, int, String, String-代理服务器配置(主机、端口、用户名、密码)

生产环境中网络可能不稳定,建议实现自动重连:

import tech.smartboot.feat.core.client.WebSocketClient;
import tech.smartboot.feat.core.client.WebSocketListener;
import tech.smartboot.feat.core.client.WebSocketResponse;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ReconnectDemo {
private static final String WS_URL = "ws://localhost:8080/ws";
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private static WebSocketClient client;
public static void main(String[] args) {
connect();
// 程序退出时关闭资源
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
scheduler.shutdown();
if (client != null) {
client.close();
}
}));
}
private static void connect() {
client = new WebSocketClient(WS_URL);
client.options().debug(true);
client.connect(new WebSocketListener() {
@Override
public void onOpen(WebSocketClient client, WebSocketResponse response) {
System.out.println("连接成功");
}
@Override
public void onMessage(WebSocketClient client, String message) {
System.out.println("收到消息: " + message);
}
@Override
public void onClose(WebSocketClient client, WebSocketResponse response, CloseReason reason) {
System.out.println("连接关闭: " + reason);
scheduleReconnect();
}
@Override
public void onError(WebSocketClient client, WebSocketResponse response, Throwable throwable) {
System.out.println("连接错误: " + throwable.getMessage());
scheduleReconnect();
}
});
}
private static void scheduleReconnect() {
System.out.println("5 秒后尝试重连...");
scheduler.schedule(ReconnectDemo::connect, 5, TimeUnit.SECONDS);
}
}

重连要点:

  • onCloseonError 回调中触发重连
  • 使用定时器延迟重连,避免频繁重试
  • 程序退出时正确释放资源

方法说明
WebSocketClient(String url)构造方法,支持 ws://wss://
options()获取配置对象
connect(WebSocketListener)建立连接
sendMessage(String)发送文本消息
sendBinary(byte[])发送二进制消息
close()关闭连接
方法触发时机
onOpen(client, response)连接建立成功
onMessage(client, String)收到文本消息
onMessage(client, byte[])收到二进制消息
onClose(client, response, reason)连接关闭
onError(client, response, throwable)发生错误