概括
WebSocket是一种服务端和网页之间的通讯协议,服务端跟网页保持着长连接,可以达到服务端主动给网页发消息的功能。
常用场景:Web聊天室、通知和紧急告警、网页消息通信、物联网通讯。
SpringBoot整合WebSocket
步骤:
1.导入WebSocket依赖
2.编写WebSocket处理器
3.编写WebSocket处理器路由
4.编写前端代码
导入WebSocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
编写WebSocket处理器路由
import lombok.extern.java.Log;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* WebSocket处理器
* @version 1.0
* @author terry
* @date 2022/7/4
*/
@Component
@Log
public class WebSocketHandler implements org.springframework.web.socket.WebSocketHandler {
public static Map<String, WebSocketSession> sshMap = new ConcurrentHashMap<>();
/**
* 用户连接上WebSocket的回调
* @param webSocketSession
*/
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) {
log.info("用户 连接WebSocket");
sshMap.put(UUID.randomUUID().toString(), webSocketSession);
}
/**
* 收到消息的回调
* @param webSocketSession
* @param webSocketMessage
*/
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) {
log.info("用户发送消息");
}
/**
* 出现错误的回调
* @param webSocketSession
* @param throwable
*/
@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) {
log.info("数据传输错误");
}
/**
* 连接关闭的回调
* @param webSocketSession
* @param closeStatus
*/
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) {
log.info("用户断开连接");
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
编写WebSocket处理器路由
import com.terry.handler.WebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* websocket 配置
* @version 1.0
* @author terry
* @date 2022/7/4
*/
@Configuration
@EnableWebSocket
public class WebSSHWebSocketConfig implements WebSocketConfigurer{
@Autowired
WebSocketHandler webSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
//socket通道
//指定处理器和路径
webSocketHandlerRegistry.addHandler(webSocketHandler, "/websocket")
.setAllowedOrigins("*");
}
}
编写前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket demo</title>
</head>
<body>
</body>
<script>
let socket = new WebSocket("ws://localhost:8080/websocket");
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
document.write("<p>" + msg.data + "</p>")
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
</script>
</html>
测试类发送消息
import com.terry.handler.WebSocketHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import java.io.IOException;
/**
* 测试发送消息
* @author terry
* @version 1.0
* @date 2022/7/11 16:44
*/
@Controller
public class TestCtrl {
@RequestMapping("/testWebSocket")
@ResponseBody
public String testWebSocket(){
WebSocketHandler.sshMap.forEach((k, v) -> {
TextMessage textMessage = new TextMessage(" Hello websocket ! ");
try {
v.sendMessage(textMessage);
} catch (IOException e) {
e.printStackTrace();
}
});
return "发送成功!";
}
@RequestMapping("/")
public String index(){
return "index";
}
}
打开前端界面效果