要做一个通讯监测方面的事变,须要及时举行前后端的的音讯推送,这里不剖析Ajax轮询和WebSocket的区分,网上讲的挺多的,下图是二者的通讯示意图,这里只写怎样用。
下图是我的一个页面简朴展现
上代码
前端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设置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
设置类
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;
运用的时刻直接用
simpMessage.convertAndSend("/topic/ip", "给前端推送的音讯" );//这里的“topic/ip"是本身设定的地点,只要和前端保持一致就能够
假如有不清楚的处所能够给我发邮件:736812983@qq.com,也能够加qq