Java WebSocket客户端
方式一 使用Java-WebSocket
1.依赖
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</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.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</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();
}
}
}
文章来源地址https://www.toymoban.com/news/detail-596371.html
文章来源:https://www.toymoban.com/news/detail-596371.html
到了这里,关于Java WebSocket客户端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!