Java WebSocket客户端

注意事项:

1.@Scheduled(fixedDelay = 5000)

2.心跳检测

3.导入依赖与导包

<dependency>
  <groupId>org.java-websocket</groupId>
  <artifactId>Java-WebSocket</artifactId>
  <version>1.5.2</version>
</dependency> 

import org.java_websocket.client.WebSocketClient;

import org.java_websocket.handshake.ServerHandshake;

 

以下这个类直接复制就可以

/**
 * @author jianhan
 * @Description: WebsocketClient客户端
 * @date 2022/11/7 16:56
 */
public class WebsocketClient extends WebSocketClient {
    private static Logger logger = LoggerFactory.getLogger(WebsocketClient.class);

    public WebsocketClient(URI url) {
        super(url);
    }

    @Override
    public void onOpen(ServerHandshake shake) {
        logger.info("握手...");
        for(Iterator<String> it = shake.iterateHttpFields(); it.hasNext();) {
            String key = it.next();
            logger.info(key+":"+shake.getFieldValue(key));
        }
    }

    @Override
    public void onMessage(String paramString) {
        logger.info("接收到消息:"+paramString);
        //以下为业务逻辑处理
        SocketClient socketClient = new SocketClient();
        socketClient.message(paramString);
    }


    @Override
    public void onClose(int paramInt, String paramString, boolean paramBoolean) {
        logger.info("关闭...");
    }

    @Override
    public void onError(Exception e) {
        logger.error("异常"+e);
    }
}

 

第二个类,逻辑处理

/**
 * @author jianhan
 * @Description: WebsocketClient客户端
 * @date 2022/11/7 17:02
 */
@Component
public class SocketClient {
    private static Logger logger = LoggerFactory.getLogger(SocketClient.class);

    @Resource
    private WebSocket webSocket;

    /**
     * @Description: 客户端建立连接
     * @Param:
     * @return:
     * @Author: jianhan
     * @Date: 2022-11-08 09:58:57
     **/
    @Scheduled(fixedDelay = 5000)
    public static void client() {
        try {
            WebsocketClient myClient = new WebsocketClient(new URI("ws://127.0.0.1:8001/webSocket"));
            myClient.connect();
            if (!myClient.getReadyState().equals(ReadyState.OPEN) && !myClient.isOpen()) {
                System.out.println("连接中。。。");
                Thread.sleep(1000 * 5);
            }
            // 连接成功往websocket服务端发送数据
            myClient.send("初始化连接成功");
            healthCheck(myClient);//心跳检测
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 心跳检测
     * @Param:
     * @return:
     * @Author: jianhan
     * @Date: 2022-11-11 09:20:03
     **/
    public static void healthCheck(WebsocketClient websocketClient) {
        try {
            while (true) {
                logger.info("进入心跳检测");
                if (websocketClient.getReadyState().equals(ReadyState.OPEN)) {
                    websocketClient.send("ping");
                    try {
                        Thread.sleep(1000 * 60 * 20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    websocketClient.connect();
                }
            }
        } catch (Exception e) {
            logger.error("客户端心跳消息发送异常");
            e.printStackTrace();
        }
    }

    /**
     * @Description: 处理接收的数据
     * @Param: message
     * @return:
     * @Author: jianhan
     * @Date: 2022-11-07 17:36:49
     **/
    public void message(String message) {
        logger.info("message:" + message);
        String string = JSON.toJSONString(message);
        Map map = (Map) JSON.parse(string);
       //以下业务代码
    }
}

 

以下为选择复制

4.websocket本身有重连机制,设置心跳检测可以延缓时间,可以不设置心跳检测,不过在client()中要if要改为while,并且在while中调client()。

while (!myClient.getReadyState().equals(ReadyState.OPEN) && !myClient.isOpen()) {
                System.out.println("连接中。。。");
                Thread.sleep(1000 * 5);
             client() 
 }    

 

posted @ 2022-11-11 17:19  Sjh_code  阅读(1235)  评论(0编辑  收藏  举报