编辑
2024-07-22
实用工具
00
请注意,本文编写于 254 天前,最后修改于 251 天前,其中某些信息可能已经过时。

目录

Java_webSocket实现
依赖引入
配置类
客户端类-基础模板
增加断线重连机制
客户端的onClose方法需要增加重试方法调用
webSocekt配置重连

Java_webSocket实现

依赖引入

xml
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.5.3</version> <!-- 使用最新版本 --> </dependency>

配置类

目的是项目启动的时候自动去连接webSocket地址

java
import com.lhw.WsRobClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; import java.net.URI; import java.net.URISyntaxException; @Configuration public class WebSocketConfig { @Value("${websocket.url}") private String url; @Bean public WsRobClient wsClient() throws URISyntaxException { WsRobClient client=new WsRobClient(new URI(url)); client.connect(); return client; } }

客户端类-基础模板

java
package com.lhw.client; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import java.util.concurrent.CopyOnWriteArrayList; /** * webSocket客户端,链接第三方使用 */ @Slf4j public class WsClient extends WebSocketClient { public static boolean isConnect=false; public static CopyOnWriteArrayList<RobInfoRes> wsRobInfos = new CopyOnWriteArrayList<>(); public WsClient(URI serverUri) { super(serverUri); } @PostConstruct public void init() { //编写初始化的代码 } @Override public void onOpen(ServerHandshake handshakedata) { log.info("链接到webSocket服务器:"+ WsClient.super.uri); // 发送消息给服务器 //this.send("Hello, Server!"); } @Override public void onMessage(String message) { System.out.println("客户端收到消息: " + message); //处理消息 } public WsRobClient(URI serverUri) { super(serverUri); log.info("链接到webSocket服务器:" + WsRobClient.super.uri); isConnect = true; } @Override public void onOpen(ServerHandshake handshakedata) { log.info("链接到webSocket服务器:" + WsRobClient.super.uri); // 发送消息给服务器 //this.send("Hello, Server!"); } @Override public void onClose(int code, String reason, boolean remote) { isConnect=false; String message="webSocket链接关闭:" + reason; log.error(message); } @Override public void onError(Exception ex) { ex.printStackTrace(); } }

增加断线重连机制

客户端的onClose方法需要增加重试方法调用

java
public void onClose(int code, String reason, boolean remote) { isConnect = false; String message = "webSocket链接关闭:" + reason; log.error(message); //重新连接服务 ReconnectClientEnum.getInstance().reconnectWs(this); }
java
import com.lhw.client.WsRobClient; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Slf4j public enum ReconnectClientEnum { WebSocketInstance(){ @Override public void reconnectWs(WsRobClient client) { cachedThreadPool.execute(new Runnable() { @Override public void run() { try { //重连间隔一分钟 Thread.sleep(60000); log.warn("重新连接"); } catch (InterruptedException e) { e.printStackTrace(); } client.reconnect(); log.info("输出连接状态:"+client.isConnect+client.getReadyState()); if (client.isClosed()){ //重新连接成功重新激活初始化方法 client.init(); } } }); } }; private static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); public abstract void reconnectWs(WsRobClient client); public static ReconnectClientEnum getInstance(){ return WebSocketInstance; } }

webSocekt配置重连

java
@Configuration public class WebSocketConfig { @Value("${websocket.url}") private String url; @Bean public WebSocketClient webSocketClient() { try { WebSocketClient webSocketClient = new MyWebSocketClient(new URI(url)); webSocketClient.connect(); Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { log.info("进入定时器"); if(webSocketClient.isClosed()){ log.error("断线重连"); webSocketClient.reconnect(); } } },1000,5000); return webSocketClient; } catch (URISyntaxException e) { e.printStackTrace(); log.error("链接失败"); } return null; } }

本文作者:Weee

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!