WebSocket 先後端實時消息推送

要作一個通訊監測方面的事情,須要實時進行先後端的的消息推送,這裏不分析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後端

相關文章
相關標籤/搜索