Springboot2模塊系列:websocket(即時消息推送)

WebSocket解析

1 配置

1.0 pom.xml

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

1.2 靜態文件加載

package com.company.system.config;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StaticResourceLoadingConfig implements WebMvcConfigurer{
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/resources/")
        .addResourceLocations("classpath:/static/")
        .addResourceLocations("classpath:/css");
    } 
}

1.2 websocket配置

package com.company.system.config;

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

/**
 * 開啓WebSocket支持
 */
@Configuration  
public class WebSocketConfig { 
    @Bean  
    public ServerEndpointExporter serverEndpointExporter() {  
        return new ServerEndpointExporter();
    }  
} 

2 Websocket路由

package com.company.system.config;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServerConfig {

    static Logger log=LoggerFactory.getLogger(WebSocketServerConfig.class);
    //當前在線連接數
    private static int onlineCount = 0;
    //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象
    private static ConcurrentHashMap<String,WebSocketServerConfig> webSocketMap = new ConcurrentHashMap<>();
    //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private Session session;
    //接收userId
    private String userId="";

    /**
     * 連接建立成功調用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在線數加1
        }

        log.info("用戶連接:"+userId+",當前在線人數爲:" + getOnlineCount());

        try {
            sendMessage("我在線上");
        } catch (IOException e) {
            log.error("用戶:"+userId+",網絡異常!!!!!!");
        }
    }

    /**
     * 連接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //從set中刪除
            subOnlineCount();
        }
        log.info("用戶退出:"+userId+",當前在線人數爲:" + getOnlineCount());
    }

    /**
     * 收到客戶端消息後調用的方法
     * @param message 發送的信息
     * @param session 會話
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用戶消息:"+userId+",報文:"+message);
        //可以羣發消息
        //消息保存到數據庫、redis
        if(StringUtils.isNotBlank(message)){
            try {
                //解析發送的報文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加發送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //傳送給對應toUserId用戶的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }else{
                    log.error("請求的userId:"+toUserId+"不在該服務器上");
                    //否則不在這個服務器上,發送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 數據傳輸錯誤
     * @param session 會話
     * @param error 錯誤
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用戶錯誤:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    
    /**
     * 服務端向客戶端推送消息
     * @param message 推送的消息
     * @throws IOException 拋出異常
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 自定義發送消息
     * @param message 發送的消息
     * @param userId 用戶ID
     * @throws IOException 拋出異常
     */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        log.info("發送消息到:"+userId+",報文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用戶"+userId+",不在線!");
        }
    }

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

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

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

3 自定義回調接口

package com.company.system.controller;

import java.util.Map;
import java.util.HashMap;

import com.company.system.config.WebSocketServerConfig;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;

@CrossOrigin(origins="*", maxAge=3600)
@RequestMapping("/websocket")
@Controller
public class MsgController {

    /**
     * web消息發送測試
     * @return
     */
    @GetMapping("/instance/message")
    public String page(){
        return "websocket/chatpage";
    }

    /**
     * 回調接口,向客戶端推送實時消息
     * @param params 消息數據結構
     * @param toUserId 發動到用戶ID
     * @return
     * @throws IOException 異常
     */
    @RequestMapping(value="/push/{toUserId}", method=RequestMethod.POST)
    @ResponseBody
    public Map pushToWeb(@RequestBody Map params,@PathVariable String toUserId) throws IOException {
        String message = params.get("message").toString();
        WebSocketServerConfig.sendInfo(message,toUserId);
        Map returnMap = new HashMap();
        returnMap.put("code", 200);
        returnMap.put("msg", "成功發送消息");
        return returnMap;
    }
}

4 對話消息展示

4.1 前端html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket即時消息</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket = null;
    function openSocket() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的瀏覽器不支持WebSocket");
        }else{
            console.log("您的瀏覽器支持WebSocket");
            //實現化WebSocket對象,指定要連接的服務器地址與端口  建立連接
            //等同於socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl="http://localhost:10106/imserver/"+$("#userId").val();
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            var username = document.getElementById("userId").value;
            var toUsername = document.getElementById("toUserId").value;
            console.log(socketUrl);
            if(socket!=null){
                socket.close();
                socket=null;
            }
            socket = new WebSocket(socketUrl);
            //打開事件
            socket.onopen = function() {
                console.log("websocket已打開");
                //socket.send("這是來自客戶端的消息" + location.href + new Date());
            };
            //獲得消息事件
            socket.onmessage = function(msg) {
                console.log("發送消息--:"+msg.data[0]);
                var contentText = "";
                if(msg.data[0] !="{"){
                    console.log("data is String");
                    contentText = msg.data;
                }else{
                    console.log(typeof msg.data);
                    contentText = JSON.parse(msg.data).contentText;
                };

                talking(contentText);
                //發現消息進入    開始處理前端觸發邏輯
            };
            //關閉事件
            socket.onclose = function() {
                console.log("websocket已關閉");
            };
            //發生了錯誤事件
            socket.onerror = function() {
                console.log("websocket發生了錯誤");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的瀏覽器不支持WebSocket");
        }else {
            console.log("您的瀏覽器支持WebSocket");
            console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
            socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
            var username = document.getElementById("userId").value;
            var sendhistory = document.getElementById("contentText").value;
            document.getElementById("content").append(username+":"+sendhistory+"\r\n");
            document.getElementById("contentText").value="";

        }
    }
    function talking(content){
        
        var toUsername = document.getElementById("toUserId").value;
        document.getElementById("content").append(toUsername+":"+content+"\r\n");
    }
</script>
<body>
<div>
    <p>當前用戶</p>
    <input id="userId" name="userId" type="text" value="小花">
    <p>好友</p>
    <input id="toUserId" name="toUserId" type="text" value="小紅">
    <p>消息記錄</p>
    <input id="contentText" name="contentText" type="text" value="你好">
</div>

<div>
    <p>操作</p>
    <button onclick="openSocket()">開啓socket</button>
    <button onclick="sendMessage()">發送消息</button>
</div>

<div>
    <h2>消息記錄</h2>
    <textarea id="content" cols="60" rows="30" readonly="readonly"></textarea>  
</div>
</body>

</html>

4.2 對話展示

瀏覽器打開兩個頁面,分別訪問:http://localhost:10106/websocket/instance/message
在這裏插入圖片描述

用戶A

在這裏插入圖片描述

用戶B

4.3 接口推送消息

在這裏插入圖片描述

接口推送消息

【參考文獻】
[1]https://blog.csdn.net/Xin_101/article/details/102665657?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522159080854619195162509630%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=159080854619195162509630&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2blogfirst_rank_v2~rank_blog_default-1-102665657.pc_v2_rank_blog_default&utm_term=websocket
[2]https://blog.csdn.net/moshowgame/article/details/80275084
[3]https://www.cnblogs.com/chenbenbuyi/p/10779999.html
[4]https://www.cnblogs.com/fangpengchengbupter/p/7823493.html
[5]https://www.cnblogs.com/csdwly/p/11733446.html
[6]https://segmentfault.com/a/1190000018340166

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