赞
踩
- <!-- sockjs -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
-
- <!-- 进行页面跳转 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- import org.springframework.context.annotation.Configuration;
- import org.springframework.messaging.simp.config.MessageBrokerRegistry;
- import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
- import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
- import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
-
- /**
- * 配置WebSocket
- */
-
- /**
- * 注册端点,发布或者订阅消息的时候需要连接此端点
- * setAllowedOrigins 非必须,*表示允许其他域进行连接
- * withSockJS 表示开始sockejs支持
- */
-
- @Configuration
- //注解开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样
- @EnableWebSocketMessageBroker
- public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
- @Override
- //注册STOMP协议的节点(endpoint),并映射指定的url
- public void registerStompEndpoints(StompEndpointRegistry registry) {
- //注册一个STOMP的endpoint,并指定使用SockJS协议
- registry.addEndpoint("/endpoint-websocket").setAllowedOrigins("*").withSockJS();
- }
-
- //配置消息代理(Message Broker)
- /**
- * 配置消息代理(中介)
- * enableSimpleBroker 服务端推送给客户端的路径前缀
- * setApplicationDestinationPrefixes 客户端发送数据给服务器端的一个前缀
- */
- @Override
- public void configureMessageBroker(MessageBrokerRegistry registry) {
- //点对点应配置一个/user消息代理,广播式应配置一个/topic消息代理
- registry.enableSimpleBroker("/topic","/user");
- //点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
- registry.setUserDestinationPrefix("/user");
- }
- }
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.messaging.handler.annotation.MessageMapping;
- import org.springframework.messaging.handler.annotation.SendTo;
- import org.springframework.messaging.simp.SimpMessagingTemplate;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import com.baidu.websocket.model.InMessage;
- import com.baidu.websocket.model.OutMessage;
- import com.baidu.websocket.model.User;
-
- @Controller
- public class GameInfoController {
-
- @RequestMapping("/index")
- public String index() {
- return "index";
- }
-
-
- @Autowired
- private SimpMessagingTemplate template;
-
- //广播推送消息
- @Scheduled(fixedRate = 10000)
- public void sendTopicMessage() {
- System.out.println("后台广播正在推送中...");
- User user=new User();
- user.setName("qushen");
- user.setAge(10);
- this.template.convertAndSend("/topic/getResponse",user);
- }
-
- }
1.SimpMessagingTemplate:SpringBoot提供操作WebSocket的对象
2.@Scheduled(fixedRate = 10000):是每十秒执行一次,记得去主类上用@EnableScheduling开启一下定时任务。
3.template.convertAndSend:直接向前端推送消息。
- <!DOCTYPE html>
- <html>
- <head>
- <title>websocket.html</title>
- <meta name="content-type" content="text/html" charset="UTF-8">
-
- </head>
- <body>
- <div>
-
- <p id="name"></p> <p id="age"></p>
-
- </div>
-
- <!-- 独立JS -->
- <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.slim.js"></script>
- <script type="text/javascript" src="js/topic.js" charset="utf-8"></script>
- <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
- <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
- </body>
- </html>
- var stompClient = null;
- //加载完浏览器后 调用connect(),打开双通道
- $(function(){
- //打开双通道
- connect()
- })
- //强制关闭浏览器 调用websocket.close(),进行正常关闭
- window.onunload = function() {
- disconnect()
- }
- function connect(){
- var socket = new SockJS('/endpoint-websocket'); //连接SockJS的endpoint名称为"endpointOyzc"
- stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
- stompClient.connect({},function(frame){//连接WebSocket服务端
- console.log('Connected:' + frame);
- //通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
- stompClient.subscribe('/topic/getResponse',function(response){
- showResponse(JSON.parse(response.body));
- });
- });
- }
-
- //关闭双通道
- function disconnect(){
- if(stompClient != null) {
- stompClient.disconnect();
- }
- console.log("Disconnected");
- }
- function showResponse(message){
- var response = $("#name");
- var response = $("#age");
- response.append("<p>"+message.name+"</p>");
- response.append("<p>"+message.age+"</p>");
- }
最后访问浏览器:http://localhost:8080/index,每十秒便可以得到如下图所示:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。