java WebSocket客户端断线重连的实现方法
前言
在工作中是否会遇到实用websocket客户端连接服务端的时候,网络波动,服务端断连的情况。会导致客户端被动断开连接。为了解决这个问题,需要对被动断开连接的情况进行捕获,并重新创建连接。这篇文章主要是提供可以直接使用的断线重连websocket客户端代码。
maven依赖
<dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <optional>true</optional> </dependency> <dependency> <groupid>cn.hutool</groupid> <artifactid>hutool-all</artifactid> <version>5.5.2</version> </dependency> <dependency> <groupid>org.java-websocket</groupid> <artifactid>java-websocket</artifactid> <version>1.5.1</version> </dependency>
代码
不废话,上代码。
package ai.guiji.csdn.ws.client; import cn.hutool.core.thread.threadutil; import cn.hutool.core.util.strutil; import lombok.extern.slf4j.slf4j; import org.java_websocket.websocket; import org.java_websocket.client.websocketclient; import org.java_websocket.framing.framedata; import org.java_websocket.handshake.serverhandshake; import javax.net.ssl.*; import java.net.socket; import java.net.uri; import java.nio.bytebuffer; import java.security.cert.certificateexception; import java.security.cert.x509certificate; import java.util.concurrent.timeunit; import java.util.concurrent.atomic.atomicboolean; import java.util.concurrent.atomic.atomicinteger; import java.util.function.consumer; /** @author huyi @date 2021/10/15 20:03 @description: 重连websocket客户端 */ @slf4j public class reconnectwebsocketclient { /** 字符串消息回调 */ private consumer<string> msgstr; /** 字节流消息回调 */ private consumer<bytebuffer> msgbyte; /** 异常回调 */ private consumer<exception> error; /** 连接标识 */ private string key; /** ws服务端连接 */ private uri serveruri; /** 尝试重连标识 */ private atomicboolean tryreconnect; /** 需要ping标识 */ private atomicboolean needping; /** websocket连接实体 */ private websocketclient websocketclient; /** 重连次数 */ private atomicinteger reconnecttimes; /** 连接结束标识 */ private atomicboolean end; /** 连接后初始发送报文,这里也可以不需要,如果服务端主动断开连接,重连后可以继续推送报文的话。 */ private string initreconnectreq; /** 结束回调 */ private consumer<string> endconsumer; public reconnectwebsocketclient( uri serveruri, string key, consumer<string> msgstr, consumer<bytebuffer> msgbyte, consumer<exception> error) { this.msgstr = msgstr; this.msgbyte = msgbyte; this.error = error; this.key = key; this.serveruri = serveruri; this.tryreconnect = new atomicboolean(false); this.needping = new atomicboolean(true); this.reconnecttimes = new atomicinteger(0); this.end = new atomicboolean(false); this.endconsumer = this::close; init(); } /** 初始化连接 */ public void init() { // 创建连接 createwebsocketclient(); // ping线程 circleping(); } private void needreconnect() throws exception { threadutil.sleep(10, timeunit.seconds); int cul = reconnecttimes.incrementandget(); if (cul > 3) { close("real stop"); throw new exception("服务端断连,3次重连均失败"); } log.warn("[{}]第[{}]次断开重连", key, cul); if (tryreconnect.get()) { log.error("[{}]第[{}]次断开重连结果 -> 连接正在重连,本次重连请求放弃", key, cul); needreconnect(); return; } try { tryreconnect.set(true); if (websocketclient.isopen()) { log.warn("[{}]第[{}]次断开重连,关闭旧连接", key, cul); websocketclient.closeconnection(2, "reconnect stop"); } websocketclient = null; createwebsocketclient(); connect(); if (strutil.hasblank(initreconnectreq)) { send(initreconnectreq); } } catch (exception exception) { log.error("[{}]第[{}]次断开重连结果 -> 连接正在重连,重连异常:[{}]", key, cul, exception.getmessage()); needreconnect(); } finally { tryreconnect.set(false); } } private void createwebsocketclient() { websocketclient = new websocketclient(serveruri) { @override public void onopen(serverhandshake serverhandshake) { log.info("[{}]reconnectwebsocketclient [onopen]连接成功{}", key, getremotesocketaddress()); tryreconnect.set(false); } @override public void onmessage(string text) { log.info("[{}]reconnectwebsocketclient [onmessage]接收到服务端数据:text={}", key, text); msgstr.accept(text); } @override public void onmessage(bytebuffer bytes) { log.info("[{}]reconnectwebsocketclient [onmessage]接收到服务端数据:bytes={}", key, bytes); msgbyte.accept(bytes); } @override public void onwebsocketpong(websocket conn, framedata f) { log.info( "[{}]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode={}", key, f.getopcode()); } @override public void onclose(int i, string s, boolean b) { log.info("[{}]reconnectwebsocketclient [onclose]关闭,s={},b={}", key, s, b); if (strutil.hasblank(s) || s.contains("https")) { if (end.get()) { return; } try { needreconnect(); } catch (exception exception) { endconsumer.accept("reconnect error"); error.accept(exception); } } } @override public void onerror(exception e) { log.info("[{}]reconnectwebsocketclient [onerror]异常,e={}", key, e); endconsumer.accept("error close"); error.accept(e); } }; if (serveruri.tostring().contains("wss://")) { trustallhosts(websocketclient); } } public void circleping() { new thread( () -> { while (needping.get()) { if (websocketclient.isopen()) { websocketclient.sendping(); } threadutil.sleep(5, timeunit.seconds); } log.warn("[{}]ping循环关闭", key); }) .start(); } /** * 连接 * * @throws exception 异常 */ public void connect() throws exception { websocketclient.connectblocking(10, timeunit.seconds); } /** * 发送 * * @param msg 消息 * @throws exception 异常 */ public void send(string msg) throws exception { this.initreconnectreq = msg; if (websocketclient.isopen()) { websocketclient.send(msg); } } /** * 关闭 * * @param msg 关闭消息 */ public void close(string msg) { needping.set(false); end.set(true); if (websocketclient != null) { websocketclient.closeconnection(3, msg); } } /** * 忽略证书 * * @param client */ public void trustallhosts(websocketclient client) { trustmanager[] trustallcerts = new trustmanager[] { new x509extendedtrustmanager() { @override public void checkclienttrusted( x509certificate[] x509certificates, string s, socket socket) throws certificateexception {} @override public void checkservertrusted( x509certificate[] x509certificates, string s, socket socket) throws certificateexception {} @override public void checkclienttrusted( x509certificate[] x509certificates, string s, sslengine sslengine) throws certificateexception {} @override public void checkservertrusted( x509certificate[] x509certificates, string s, sslengine sslengine) throws certificateexception {} @override public void checkclienttrusted(x509certificate[] x509certificates, string s) throws certificateexception {} @override public void checkservertrusted(x509certificate[] x509certificates, string s) throws certificateexception {} @override public x509certificate[] getacceptedissuers() { return null; } } }; try { sslcontext ssl = sslcontext.getinstance("ssl"); ssl.init(null, trustallcerts, new java.security.securerandom()); sslsocketfactory socketfactory = ssl.getsocketfactory(); client.setsocketfactory(socketfactory); } catch (exception e) { log.error("reconnectwebsocketclient trustallhosts 异常,e={0}", e); } } }
代码说明:
1、参数的重连次数可以配置。
2、增加异步pingpong线程,一旦结束连接会自动关闭。
3、对字符串、字节流、异常都有回调措施。
测试代码方法
public static void main(string[] args) throws exception { reconnectwebsocketclient client = new reconnectwebsocketclient( new uri(string.format("wss://192.168.1.77:24009")), "test", // 字符串消息处理 msg -> { // todo 字符串消息处理 system.out.println("字符串消息:" + msg); }, null, // 异常回调 error -> { // todo 字符串消息处理 system.out.println("异常:" + error.getmessage()); }); client.connect(); client.send("haha"); }
验证结果
16:08:54.468 [websocketconnectreadthread-12] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onopen]连接成功/192.168.1.77:24009
16:08:54.475 [websocketconnectreadthread-12] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onmessage]接收到服务端数据:text=connect success from tcp4:192.168.6.63:11018!
字符串消息:connect success from tcp4:192.168.6.63:11018!
16:08:56.080 [websocketconnectreadthread-12] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onclose]关闭,s=,b=true
16:09:06.097 [websocketconnectreadthread-12] warn ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]第[1]次断开重连
16:09:06.150 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onopen]连接成功/192.168.1.77:24009
16:09:06.150 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onmessage]接收到服务端数据:text=connect success from tcp4:192.168.6.63:11038!
字符串消息:connect success from tcp4:192.168.6.63:11038!
16:09:09.369 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:14.370 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:19.371 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:24.379 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:29.382 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:34.398 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:39.402 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:44.404 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:49.415 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:54.429 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:09:59.437 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:10:04.449 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:10:06.154 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:10:09.455 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:10:14.462 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:10:19.468 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onwebsocketpong]接收到服务端数据:opcode=pong
16:10:19.644 [websocketconnectreadthread-16] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onclose]关闭,s=,b=true
16:10:29.654 [websocketconnectreadthread-16] warn ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]第[2]次断开重连
16:10:31.710 [websocketconnectreadthread-19] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onerror]异常,e={}
java.net.connectexception: connection refused: connect
at java.net.dualstackplainsocketimpl.connect0(native method)
at java.net.dualstackplainsocketimpl.socketconnect(dualstackplainsocketimpl.java:79)
at java.net.abstractplainsocketimpl.doconnect(abstractplainsocketimpl.java:350)
at java.net.abstractplainsocketimpl.connecttoaddress(abstractplainsocketimpl.java:206)
at java.net.abstractplainsocketimpl.connect(abstractplainsocketimpl.java:188)
at java.net.plainsocketimpl.connect(plainsocketimpl.java:172)
at java.net.sockssocketimpl.connect(sockssocketimpl.java:392)
at java.net.socket.connect(socket.java:589)
at sun.security.ssl.sslsocketimpl.connect(sslsocketimpl.java:673)
at org.java_websocket.client.websocketclient.run(websocketclient.java:461)
at java.lang.thread.run(thread.java:748)
16:10:31.710 [websocketconnectreadthread-19] info ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]reconnectwebsocketclient [onclose]关闭,s=error close,b=false
异常:connection refused: connect
16:10:34.473 [thread-0] warn ai.guiji.csdn.ws.client.reconnectwebsocketclient - [test]ping循环关闭
这里我才用的是手动关闭服务端方式触发,客户端被动断连情况。重连两次,第二次服务端还未启动导致异常触发。
到此这篇关于java websocket客户端断线重连的实现方法的文章就介绍到这了,更多相关java websocket客户端断线重连内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!