web socket集成spring boot

後端代碼

首先加入pom文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <!-- <version>1.3.5.RELEASE</version> -->
        </dependency>

加入配置類

@Configuration
public class WebSocketConfig {

    /**
     * 	注入ServerEndpointExporter,
     * 	這個bean會自動註冊使用了@ServerEndpoint註解聲明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

加入連接發送消息方法

@Component
@ServerEndpoint("/websocket/{userName}")
// 此註解相當於設置訪問URL
public class WebSocket {

    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private final static Logger logger = LoggerFactory.getLogger(LoginIntercept.class);

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName) {
        this.session = session;
        webSockets.add(this);
        if (sessionPool.containsKey(userName)) {
            sessionPool.put(userName + String.valueOf(session.getId()), session);
        } else {
            sessionPool.put(userName, session);
        }
        logger.info("【websocket消息】有新的連接,總數爲:" + webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("【websocket消息】連接斷開,總數爲:" + webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客戶端消息:" + message);
    }

    /**
     * 功能描述: 此爲廣播消息
     *
     * @param: [message] (消息)
     * @return: void ()
     */
    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            logger.info("【websocket消息】廣播消息:" + message);
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 功能描述:此爲單點消息 (發送文本) 現在可以發送給多客戶端
     *
     * @param: [userName, message] (接收人,發送消息)
     * @return: void ()
     */
    public void sendTextMessage(String userName, String message) {
        // 遍歷sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在當前用戶
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 功能描述: 此爲單點消息 (發送文本) 現在可以發送給多客戶端
     *
     * @param: [userName, message] (接收人,發送消息)
     * @return: void ()
     */
    public void sendObjMessage(String userName, Object message) {
        // 遍歷sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在當前用戶
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendObject(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

前段代碼

import sysConfig from "../config";
import {Notification} from 'element-ui';
import {EVENT_TYPE} from "../const";
export function openSocket(userId) {
  let ws = new WebSocket(`${sysConfig.SOCKET_URL}/${userId}`);
  // let ws = new WebSocket(`ws://121.40.165.18:8800`);
  ws.onopen = function (evt) {
    Notification({
      title: '歡迎回來!',
      message: `${sysConfig.SOCKET_URL}/${userId}`
    });
  };
  ws.onmessage = function (e) {
    console.log(typeof e.data);
    try{
      if(e.data!=undefined || e.data!=null){
        let json= JSON.parse(e.data);
        Notification({
          title: json.messageTitle,
          message: json.messageText
        });
        //通知頁面更新
        window.postMessage(EVENT_TYPE.updateMessage,'/');
      }
    }catch(err){
        console.log("webSocke異常,異常信息:"+err)
    }


    //ws.close();
  };
  ws.onclose = function (evt) {
    console.log('Connection closed.');
  };
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章