webSocket實現后台給前台通知


  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
  </dependency>

webSocket的配置類

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

/**
 * @ClassName: WebSocketConfig
 * @Auther: zhaoxiuhao
 * @Date: 2020/12/5 17:33
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpoint() {

        return new ServerEndpointExporter();
    }
}

websocket的連接監聽

 

package com.example.websocket;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
@ServerEndpoint("/webSocket/{username}")
@Component
public class WebSocket {
    private static int onlineCount = 0;
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private Session session;
    private String username;

    public WebSocket() {
        System.out.println(1111);
    }
    /**
     * 建立連接的時候
     **/
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {

        this.username = username;
        this.session = session;

        addOnlineCount();
        clients.put(username, this);
        System.out.println("已連接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        String mes= jsonObject.getString("message");
        if (!jsonObject.getString("To").equals("All")) {
            sendMessageTo(mes, jsonObject.getString("To"));
        } else {
            sendMessageAll("給所有人");
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
  //給某個人發送信息
    public void sendMessageTo(String message, String To) throws IOException {
        for (WebSocket item : clients.values()) {
            if (item.username.equals(To) )
                item.session.getAsyncRemote().sendText(message);
        }
    }
  //給所有人發送信息
    public void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }

    public Session getSession() {
        return session;
    }
}

 

 

 

主動調用后台的方法推送信息

package com.example.websocket;

import com.example.websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * @ClassName: WebSocketController
 * @Auther: zhaoxiuhao
 * @Date: 2020/12/5 16:20
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/socket")
public class WebSocketController {
    @Autowired
    private WebSocket webSocket;
    @RequestMapping("/sendMessage")
    public void sendMessage(@RequestParam("message")String message) throws IOException {
        webSocket.sendMessageAll(message);

    }
    
}

 前端建立websocket連接

 mounted() {
      var host = document.location.host;
      const url = 'ws://192.168.0.102:8081/'  + 'webSocket/' + "user";
        var websocket = null
     // alert(url)
     if ('WebSocket' in window) {
          websocket = new WebSocket(url);
           //alert("支持WebSocket協議");
      } else {
          alert("不支持WebSocket協議");
      }
    
      //WebSocket連接發生錯誤的回調方法
    websocket.onerror = function () {
        console.log("連接失敗")
    };

    //WebSocket連接成功建立的回調方法
    websocket.onopen = function () {
        console.log("WebSocket連接成功");
    };

    //接收到消息的回調方法
    websocket.onmessage = (event)=> {
        console.log("接收到推送過來的信息",event.data)
          this.$notify({
            showClose: true,
            message: '單擊'+JSON.stringify(event.data),
            type: 'success',
          });
        // websocket.close();
        // alert("webSocket已關閉!")
    };

    //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
    window.onbeforeunload = function () {
        //closeWebSocket();
    };

    //關閉WebSocket連接
    function closeWebSocket() {
        websocket.close();
    }

    //連接關閉的回調方法
    websocket.onclose = function () {
         console.log("WebSocket連接關閉");
    };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM