java实现WebSocket客户端&&断线重连机制

1、引入maven依赖(注意版本)


    org.java-websocket
    Java-WebSocket
    1.5.3

2、代码

@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);
    }
}

你可能感兴趣的:(websocket,java,java,websocket)