一、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!--websocket-->
<dependency>
<groupId>io.goeasy</groupId>
<artifactId>goeasy-sdk</artifactId>
<version>0.4.2</version>
</dependency>
二、具体步骤
-
建立连接:通过调用 WebSocket 对象的 open() 方法来建立与服务器的连接。
-
发送数据:通过调用 WebSocket 对象的 send() 方法来向服务器发送数据。
-
接收数据:通过 WebSocket 对象的 onmessage 事件来接收服务器发送回来的数据。
-
关闭连接:通过调用 WebSocket 对象的 close() 方法来关闭与服务器的连接
三、代码实例
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
//建立两个链接
private final MyWebSocketHandler myWebSocketHandler;
private final MyWebSocketHandler1 myWebSocketHandler1;
public WebSocketConfig(MyWebSocketHandler myWebSocketHandler, MyWebSocketHandler1 myWebSocketHandler1) {
this.myWebSocketHandler = myWebSocketHandler;
this.myWebSocketHandler1 = myWebSocketHandler1;
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//分别监听不同的实例
registry.addHandler(myWebSocketHandler, "/websocket")
.setAllowedOrigins("*");
registry.addHandler(myWebSocketHandler1, "/websocket2")
.setAllowedOrigins("*");
}
}
这里以监听字符串为例子(可以选择监听文件等)
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
private WebSocketSession session;
public static String logContent = ""; // 字符串内容
private long lastLength = 0; // 上次记录的字符串长度
@Override
public void afterConnectionEstablished(WebSocketSession session){
// 处理WebSocket连接建立的逻辑
this.session = session;
// 启动字符串监控线程
Thread stringMonitoringThread = new Thread(() -> {
while (true) {
if (logContent.length() > lastLength) {
String modifiedContent = logContent.substring((int) lastLength); // 获取新增的字符串内容
try {
session.sendMessage(new TextMessage(modifiedContent)); // 发送新增的内容到前台
logContent="";
} catch (IOException e) {
throw new RuntimeException(e);
}
lastLength = logContent.length(); // 更新上次记录的字符串长度
}
try {
Thread.sleep(1000); // 每隔一秒检查一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
stringMonitoringThread.start(); // 启动字符串监控线程
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的WebSocket消息的逻辑
System.out.println("接收到WebSocket消息:" + message.getPayload());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 处理WebSocket连接关闭的逻辑
System.out.println("WebSocket连接已关闭");
}
}
模拟用法
@PostMapping("/send")
public void send(@RequestBody SourceTypeResponse sourceTypeResponse){
log.info(JSONObject.toJSONString(sourceTypeResponse));
if (sourceTypeResponse.getPageNum()==1){
MyWebSocketHandler.logContent= "警告";
}
}
四、前台展示
mounted() {
const socket = new WebSocket('ws://127.0.0.1:8087/websocket')
socket.onopen = () => {
console.log('WebSocket连接已建立')
}
socket.onmessage = event => {
const logMessage = event.data
console.log(logMessage)
this.logs.push(logMessage) // 将日志消息存储到数组中
}
socket.onclose = () => {
console.log('WebSocket连接已关闭')
}
socket.onerror = error => {
console.error('WebSocket发生错误:', error)
}
},
<div>
<h1>WebSocket日志</h1>
<ul>
<li v-for="log in logs" :key="log">{{ log }}</li>
</ul>
</div>