1、引入maven依赖(注意版本)文章来源:https://www.toymoban.com/news/detail-568083.html
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.5.3</version> </dependency>
2、代码文章来源地址https://www.toymoban.com/news/detail-568083.html
@ServerEndpoint(value = "/websocket/inside/{userId}")
@Slf4j
@Component
public class WebSocketClientServer {
public static WebSocketClient client;
@PostConstruct
public void connnet() {
try {
client = new WebSocketClient(new URI("webscoket连接地址"), new Draft_6455()) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info("握手成功");
}
@Override
public void onMessage(String msg) {
//业务处理
}
@Override
public void onClose(int i, String s, boolean b) {
log.info("连接已关闭");
}
@Override
public void onError(Exception e) {
e.printStackTrace();
log.info("发生错误已关闭");
}
};
} catch (URISyntaxException e) {
e.printStackTrace();
}
/**
* 重连机制
* 使用 ScheduledExecutorService 不要使用timer timer不支持多线程,挂在timer下的任务都是单线程,如果任务运行时间过长影响其他任务运行
*
* ScheduledThreadPoolExecutor支持多线程。同一时候在线程中对异常进行了捕获。
*
* */
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try{
if(client.getReadyState()!= ReadyState.OPEN) {
if(client.getReadyState()== ReadyState.NOT_YET_CONNECTED) {
if(client.isClosed()) {
log.info("连接关闭,正在重新连接中……");
client.reconnect();
}else{
log.info("建立连接中……");
client.connect();
}
}else if( client.getReadyState() == ReadyState.CLOSED){
log.info("连接关闭,正在重新连接中……");
client.reconnect();
}
}
}catch(Exception e) {
log.error("连接异常,正在重新连接中……");
client.reconnect();
}
}
},0,6000, TimeUnit.MILLISECONDS);
}
}
到了这里,关于java实现WebSocket客户端&&断线重连机制的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!