WebSocket 客户端
This content is not available in your language yet.
WebSocket 协议支持客户端与服务器之间的全双工通信,适用于实时聊天、在线游戏、股票行情推送、物联网设备控制等场景。Feat 提供了简洁的 WebSocketClient API 来实现 WebSocket 客户端功能。
建立连接并收发消息
Section titled “建立连接并收发消息”以下示例展示 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()); } }); }}核心步骤:
- 创建客户端 - 通过 URL 构造
WebSocketClient,支持ws://和wss://协议 - 实现监听器 - 实现
WebSocketListener接口处理各类事件 - 建立连接 - 调用
connect()方法发起连接
发送不同类型消息
Section titled “发送不同类型消息”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"); // 代理配置| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
connectTimeout | int | 30000 | 连接超时时间(毫秒) |
readBufferSize | int | 4096 | 读缓冲区大小(字节) |
writeBufferSize | int | 4096 | 写缓冲区大小(字节) |
debug | boolean | false | 是否输出调试日志 |
proxy | String, int, String, String | - | 代理服务器配置(主机、端口、用户名、密码) |
实现重连机制
Section titled “实现重连机制”生产环境中网络可能不稳定,建议实现自动重连:
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); }}重连要点:
- 在
onClose和onError回调中触发重连 - 使用定时器延迟重连,避免频繁重试
- 程序退出时正确释放资源
API 速查
Section titled “API 速查”WebSocketClient 方法
Section titled “WebSocketClient 方法”| 方法 | 说明 |
|---|---|
WebSocketClient(String url) | 构造方法,支持 ws:// 和 wss:// |
options() | 获取配置对象 |
connect(WebSocketListener) | 建立连接 |
sendMessage(String) | 发送文本消息 |
sendBinary(byte[]) | 发送二进制消息 |
close() | 关闭连接 |
WebSocketListener 回调
Section titled “WebSocketListener 回调”| 方法 | 触发时机 |
|---|---|
onOpen(client, response) | 连接建立成功 |
onMessage(client, String) | 收到文本消息 |
onMessage(client, byte[]) | 收到二进制消息 |
onClose(client, response, reason) | 连接关闭 |
onError(client, response, throwable) | 发生错误 |
- 了解 HTTP 客户端 发送 HTTP 请求
- 了解 SSE 客户端 实现服务器推送
- 查看 WebSocketClient 源码