Java-WebSocket连接socket

经正祥
2023-12-01

依赖

<dependency>
            <!-- 建立客户端链接-->
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.5.3</version>
        </dependency>

连接代码就这么简单别怀疑

package com.dataexa.qt.websocket;


import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.URI;

/**
 * websocket客户端监听类
 *
 * @author 。
 */
public class BaseWebsocketClient extends WebSocketClient {

    private static Logger logger = LoggerFactory.getLogger(BaseWebsocketClient.class);

    public BaseWebsocketClient(URI serverUri) {
        super(serverUri);
    }


    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        logger.info(">>>>>>>>>>>websocket open");

    }

    @Override
    public void onMessage(String s) {
        logger.info(">>>>>>>>>> websocket message");
        System.out.println(s);

    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.info(">>>>>>>>>>>websocket close");
    }

    @Override
    public void onError(Exception e) {
        logger.error(">>>>>>>>>websocket error {}", e);
    }


}

以下方法加在业务层即可.


	@Value("${spring.socket.url}")
    private String url;

  public  void webSocketStata(){
        try {
            BaseWebsocketClient baseWebsocketClient= new BaseWebsocketClient( new URI(url));
            baseWebsocketClient.connect();
            while (!baseWebsocketClient.getReadyState().equals(ReadyState.OPEN)){
                log.info("链接中....");
                Thread.sleep(1000);
                break;
            }
              log.info("状态 :{}",baseWebsocketClient.isOpen());
            if (baseWebsocketClient.isOpen()){
               System.out.println("在线状态");
            }else {
             System.out.println("离线状态");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
 类似资料: