创建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中的代码页可以简化为如下