Java WebSocket客户端

Java WebSocket客户端

方式一 使用Java-WebSocket

1.依赖

<dependency>
    <groupId>org.java-websocketgroupId>
    <artifactId>Java-WebSocketartifactId>
    <version>1.5.3version>
dependency>

2.代码

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhong
 */
public class MyWebSocketClient extends WebSocketClient {

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

    @Override
    public void onOpen(ServerHandshake data) {
        System.out.println("WebSocket连接已打开。");
    }

    @Override
    public void onMessage(String message) {
        System.out.println("收到消息: " + message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("WebSocket连接已关闭。");
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("WebSocket连接发生错误:" + ex.getMessage());
    }

    /**
     * 连接定时检查
     */
    public void startReconnectTask(long delay,
                                   TimeUnit unit) {
        System.out.println("WebSocket 心跳检查");
        // 以下为定时器,建议使用自定义线程池,或交给框架处理(spring)
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleWithFixedDelay(() -> {
            // 检查逻辑:判断当前连接是否连通
            if (!this.isOpen()) {
                System.out.println("WebSocket 开始重连......");
                // 重置连接
                this.reconnect();
                // 以下为错误示范
                //this.close();
                //this.connect();
            }
        }, 0, delay, unit);
    }
	// 测试
    public static void main(String[] args) throws URISyntaxException {
        // 服务地址
        URI uri = new URI("ws:服务地址");
        // 创建客户端
        MyWebSocketClient myWebSocketClient = new MyWebSocketClient(uri);
        // 建立连接
        myWebSocketClient.connect();
        // 开启 定时检查
        myWebSocketClient.startReconnectTask(5, TimeUnit.SECONDS);
    }
}

方式二 spring-boot-starter-websocket

1.依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-websocketartifactId>
dependency>

2.代码

2.1 自定义 websocket handler

public class ClientWebSocketHandler implements WebSocketHandler {
    public static final Logger logger = LoggerFactory.getLogger(ClientWebSocketHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("客户端连接成功:{}", session.getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        logger.info("客户端接受到消息:{}", message.getPayload());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        logger.info("客户端发送错误:{}", exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info("客户端关闭连接:{}", closeStatus.getCode());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

2.2 将websocket handler加入容器

@Configuration
public class WebSocketClientConfig {
    @Bean
    public WebSocketClient webSocketClient() {
        return new StandardWebSocketClient();
    }

    @Bean
    public ClientWebSocketHandler clientWebSocketHandler() {
        return new ClientWebSocketHandler();
    }

    @Bean
    public WebSocketConnectionManager connectionManager() {
        WebSocketConnectionManager connectionManager = new WebSocketConnectionManager(
                webSocketClient(),
                clientWebSocketHandler(),
                "连接地址"
        );
        connectionManager.setAutoStartup(true);
        return connectionManager;
    }
}

2.3 定时器监控

@EnableScheduling
@SpringBootApplication
public class WebsocketClientApplication {
    @Resource
    private WebSocketConnectionManager connectionManager;

    public static void main(String[] args) {
        SpringApplication.run(WebsocketClientApplication.class, args);
    }
    @Scheduled(fixedRate = 5000)
    public void reconnectTask() {
        System.out.println("心跳检查");
        if(!connectionManager.isConnected()){
            System.out.println("重新连接.....");
            connectionManager.stop();
            connectionManager.start();
        }
    }

}

你可能感兴趣的:(工具,spring,boot,java,java,websocket,开发语言)