創建springboot工程,pom.xml文件中引入socket依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
創建socket核心配置類
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/endpointSang").withSockJS(); //添加終點 } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic");//開啟top代理 } }
創建controller
@Controller public class WebSocketController { @MessageMapping("/welcome") //那個請求/welcomel發來的 @SendTo("/topic/getResponse") //發到那個訂閱topic/getResponse public String getMessage(String name){ System.out.println(name); return name; } }
創建index.html網頁,記得引入相關的js文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket廣播</title>
<script src="jquery-3.4.1.js"></script>
<script src="sockjs.min.js"></script>
<script src="stomp.js"></script>
</head>
<body>
<button type="button" onclick="connent()">連接</button>
<input type="text" id="name"/>
<button type="button" onclick="sendMsg()">發送</button>
<script>
var stompClient=null;
//連接socket
function connent() {
var socket = new SockJS("/endpointSang");
stompClient= Stomp.over(socket);
stompClient.connect({},function (frame) {
stompClient.subscribe("/topic/getResponse",function (response) {
console.log(response)
})
})
}
//斷開連接
function disConnent() {
if (stompClient!=null) {
stompClient.disconnect();
}
}
//發送數據
function sendMsg() {
var name = $("#name").val();
stompClient.send("/welcome",{},JSON.stringify({"name":name}));
}
</script>
</body>
</html>
點擊連接后

發送數據后顯示

只要是訂閱/topic/getResponse的都能接收到數據。
到此,群聊演示完畢.
源代碼地址:https://github.com/duanbochao/websocket.git
備注:controller中的代碼頁可以簡化為如下

