要作一个通讯监测方面的事情,须要实时进行先后端的的消息推送,这里不分析Ajax轮询和WebSocket的区别,网上讲的挺多的,下图是二者的通讯示意图,这里只写怎么用。
下图是个人一个页面简单展现javascript
上代码
前端js
连接:https://pan.baidu.com/s/1gkdj...
提取码:c0q5
从上述链接下载必须的js
sockjs.min.js
stomp.min.js前端
<script src="dist/js/sockjs.min.js"></script> <script src="dist/js/stomp.min.js"></script> <script type="text/javascript"> function connect() { var socket = new SockJS("http://127.0.0.1:7070/myWebSocket");//若是先后端分离项目须要拼接具体地址 stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { setMessageInnerHTML("链接成功!" + "\n") console.log(frame); stompClient.subscribe('/topic/ip', function(body) {//'/topic/ip'是本身定义的一个地址,可根据本身业务定 //收到后台推送的消息后进行的业务处理,根据本身的状况写 alert("来自后台的消息:"+body.body); }); }); } </script>
后端使用
pom.xml配置java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
配置类web
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; //springBoot2.0版本后使用 实现WebSocketMessageBrokerConfigurer接口; //2.0如下版本继承AbstractWebSocketMessageBrokerConfigurer 类; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { //注册一个Stomp 协议的endpoint指定URL为myWebSocket,并用.withSockJS()指定 SockJS协议。.setAllowedOrigins("*")设置跨域 registry.addEndpoint("/myWebSocket").setAllowedOrigins("*").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry config) { //配置消息代理(message broker) //将消息传回给以‘/topic’开头的客户端 config.enableSimpleBroker("/topic"); } }
private SimpMessagingTemplate simpMessage;
使用的时候直接用spring
simpMessage.convertAndSend("/topic/ip", "给前端推送的消息" );//这里的“topic/ip"是本身设定的地址,只要和前端保持一致就能够
若是有不清楚的地方能够给我发邮件:736812983@qq.com,也能够加qq后端