java websocket断开重连

java websocket断开重连,java客户端websocket断开重连

最近一个需求。需要用java客户端的方式连接远程的webscoket 站点。需要保证连接断开自动重连,于是基于Java-WebSocket这个开源代码实现了断开重连,代码比较简单,如下,还在完善中。。。首先需要注意的是为了防止重试给远端的websocket 站点带来过大的压力,我们需要设计一个规则,重试间隔随着重试次数的增加而不断增加,防止给远端站点带来过大压力。具体代码如下:
Java-WebSocket pom

    
        org.java-websocket
        Java-WebSocket
         1.3.9     
     
package com.suning.search.common.utils;

import java.net.URI;

import java.util.Map;

import java.util.Timer;

import org.java_websocket.client.WebSocketClient;

import org.java_websocket.drafts.Draft;

import org.java_websocket.handshake.ServerHandshake;

public abstract class ReconnectingWebSocketClient extends WebSocketClient {

private boolean debug = true;

private Integer reconnectInterval = 1000;

private Integer maxReconnectInterval = 30000;

private Double reconnectDecay = 1.5;

private Integer reconnectAttempts = 0;

private Integer maxReconnectAttempts = 5000;

private Boolean forcedClose = false;

private Timer reconnectTimer;

private volatile Boolean isReconnecting = false;

private ReschedulableTimerTask reconnectTimerTask;

public ReconnectingWebSocketClient( URI serverUri , Draft protocolDraft ) {

super( serverUri, protocolDraft, null, 0 );

}

public ReconnectingWebSocketClient(URI serverUri, Draft protocolDraft, Map httpHeaders,

int connectTimeout) {

super(serverUri, protocolDraft, httpHeaders, connectTimeout);

// TODO Auto-generated constructor stub

}

@Override

public void onClose(int arg0, String arg1, boolean arg2) {

if (forcedClose) {

// 调用close 方法

close(arg0, arg1, arg2);

} else {

if (!isReconnecting) {

restartReconnectionTimer();

}

isReconnecting = true;

}

}

@Override

public void onError(Exception exception) {

error(exception);

}

@Override

public void onMessage(String message) {

message(message);

}

@Override

public void onOpen(ServerHandshake arg0) {

open(arg0);

}

private void restartReconnectionTimer() {

cancelReconnectionTimer();

reconnectTimer = new Timer("reconnectTimer");

reconnectTimerTask = new ReschedulableTimerTask() {

@Override

public void run() {

if (reconnectAttempts >= maxReconnectAttempts) {

cancelReconnectionTimer();

if (debug) {

System.out.println("以达到最大重试次数:" + maxReconnectAttempts + ",已停止重试!!!!");

}

}

reconnectAttempts++;

try {

Boolean isOpen = reconnectBlocking();

if (isOpen) {

if (debug) {

System.out.println("连接成功,重试次数为:" + reconnectAttempts);

}

cancelReconnectionTimer();

reconnectAttempts = 0;

isReconnecting = false;

} else {

if (debug) {

System.out.println("连接失败,重试次数为:" + reconnectAttempts);

}

double timeoutd = reconnectInterval * Math.pow(reconnectDecay, reconnectAttempts);

int timeout = Integer.parseInt(new java.text.DecimalFormat("0").format(timeoutd));

timeout = timeout > maxReconnectInterval ? maxReconnectInterval : timeout;

System.out.println(timeout);

reconnectTimerTask.re_schedule2(timeout);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

};

reconnectTimerTask.schedule(reconnectTimer,reconnectInterval);

}

private void cancelReconnectionTimer() {

if (reconnectTimer != null) {

reconnectTimer.cancel();

reconnectTimer = null;

}

if (reconnectTimerTask != null) {

reconnectTimerTask.cancel();

reconnectTimerTask = null;

}

}

// ABTRACT METHODS /////////////////////////////////////////////////////////

public abstract void open(ServerHandshake handshakedata);

public abstract void message(String message);

public abstract void close(int code, String reason, boolean remote);

public abstract void error(Exception ex);

}

// 另一个核心,修改java定时器的执行频率

package com.suning.search.common.utils;

import java.lang.reflect.Field;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

public abstract class ReschedulableTimerTask extends TimerTask{

public int i = 0;

public void schedule(Timer timer,int checkInterval) {

timer.scheduleAtFixedRate(this, 0, checkInterval);

}

public void re_schedule2(int newCheckInterval) {

Date now = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat(

"E MMMMM dd HH:mm:ss zzz yyyy");

System.out.println("re_schedule2:" + dateFormat.format(now).toString());

long nextExecutionTime = now.getTime() + newCheckInterval;

setDeclaredField(TimerTask.class, this, "nextExecutionTime", nextExecutionTime);

setDeclaredField(TimerTask.class, this, "period", newCheckInterval);

}

static boolean setDeclaredField(Class clazz, Object obj,

String name, Object value) {

try {

Field field = clazz.getDeclaredField(name);

field.setAccessible(true);

field.set(obj, value);

return true;

} catch (Exception ex) {

ex.printStackTrace();

return false;

}

}

}

你可能感兴趣的:(java websocket断开重连)