
点/击/蓝/字 关/注/我/们
一、背景
笔者之前的项目中需要用webSocket协议进行长连接上游供应商,笔者为此做了一些小小的技术预研,特将此记录下来。
tips:因笔者主要是连接上游供应商的服务端,因此本文主要介绍webSocket客户端的知识,暂不编写服务端知识,请见谅。
具体详细代码地址:
https://github.com/ikuncoder/webSocketConnector
二、javax
在java的扩展包javax.websocket中已经定义了一套WebSocket的接口规范,应用起来比较简单快捷。
public class MainApplication {
public static void main(String[] args) {
connect();
}
private static void connect() {
String url = "";//your websocket url,for example,wss://xxxxx.com/websocket/**
// 实例化WebSocketService
WebSocketService webSocketService = new WebSocketService();
// 打开WebSocket连接
try {
webSocketService.openWebSocketConnection(url);
//do something after connect
} catch (Exception e) {
e.printStackTrace();
}
}
}
首先创建一个WebSocketService对象,传入需要连接的url,需要是wss或者是ws开头的。
@ClientEndpoint
@Slf4j
public class WebSocketService {
private Session userSession = null;
private Long startTime = System.currentTimeMillis();
public void openWebSocketConnection(String url) {
try {
URI uri = URI.create(url);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, uri);
} catch (Exception e) {
throw new RuntimeException("Could not open WebSocket connection", e);
}
}
@OnOpen
public void onOpen(Session userSession) {
System.out.println(Thread.currentThread().getName() + " Connection opened.");
this.userSession = userSession;
}
@OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println(Thread.currentThread().getName() + "

最低0.47元/天 解锁文章
3647

被折叠的 条评论
为什么被折叠?



