Sring MVC 模式下使用websocket

前言

九風(fēng)的上一篇文章java WebSocket開發(fā)入門WebSocket介紹了websocket一些特征和提供了一個簡單的demo,但上篇文章中的websocket類不能被Spring MVC中的controller層、server層調(diào)用,這篇文章提供了一個可用于MVC模式調(diào)用的版本。

程序運行環(huán)境說明

Server version : Apache Tomcat/7.0.65
JVM version: 1.7.0_75-b13

官網(wǎng)介紹

首先推薦大家看官網(wǎng)Oracle的javax.websocket介紹 ,官網(wǎng)對其中的ServerEndpoint的介紹是:ServerEndpoint是web socket的一個端點,用于部署在URI空間的web socket服務(wù),該注釋允許開發(fā)者去定義公共的URL或URI模板端點和其他一些websocekt運行時的重要屬性,例如encoder屬性用于發(fā)送消息。

上篇文章中的最簡單的tomcat的websocket服務(wù)器如果需要在MVC模式中被其他類調(diào)用,需要配置Configurator屬性:用于調(diào)用一些自定義的配置算法,如攔截連接握手或可用于被每個端點實例調(diào)用的任意的方法和算法;對于服務(wù)加載程序,該接口必須提供默認(rèn)配置器加載平臺。

spring MVC模式配置

對于spring MVC模式,ServerEndpoint的代碼為:

@ServerEndpoint(value="/websocketTest/{userId}",configurator = SpringConfigurator.class)

需要在maven中導(dǎo)入SpringConfiguator的包:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${spring.version}</version>
</dependency>

目標(biāo)需求

平臺有多個用戶,每個用戶可能會在多個終端上登錄,當(dāng)有消息到達(dá)時,實時將所有消息推送給所有所用登錄的當(dāng)前用戶,就像QQ消息一樣,用戶在PC、pad、phone上同時登錄時,將收到的消息同時推送給該用戶的所有終端。

數(shù)據(jù)結(jié)構(gòu)設(shè)計

每個用戶對應(yīng)多個終端,多個終端用Set來記錄,用戶使用Map來記錄,所以數(shù)據(jù)存儲結(jié)構(gòu)為Map<userId, Set<Terminal>>,結(jié)合具體的數(shù)據(jù)類型就是如下所示的的存儲結(jié)構(gòu):

//記錄每個用戶下多個終端的連接
private static Map<Long, Set<WebsocketDemo>> userSocket = new HashMap<>();

操作設(shè)計

  1. onOpen: 新建連接時需要判斷是否是該用戶第一次連接,如果是第一次連接,則對Map增加一個userId;否則將sessionid添加入已有的用戶Set中。
    2.onClose:連接關(guān)閉時將該用戶的Set中記錄remove,如果該用戶沒有終端登錄了,則移除Map中該用戶的記錄
  2. onMessage: 這個根據(jù)業(yè)務(wù)情況詳細(xì)設(shè)計。
  3. 給用戶的所有終端發(fā)送數(shù)據(jù):遍歷該用戶的Set中的連接即可。

后臺websocket連接代碼

/**
 * @Class: WebsocketDemo
 * @Description:  給所用戶所有終端推送消息
 * @author JFPZ
 * @date 2017年5月15日 上午21:38:08
 */
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.server.standard.SpringConfigurator;

//websocket連接URL地址和可被調(diào)用配置
@ServerEndpoint(value="/websocketDemo/{userId}",configurator = SpringConfigurator.class)
public class WebsocketDemo {
    //日志記錄      
    private Logger logger = LoggerFactory.getLogger(WebsocketDemo.class);
    //靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的。
    private static int onlineCount = 0;
   
    //記錄每個用戶下多個終端的連接
    private static Map<Long, Set<WebsocketDemo>> userSocket = new HashMap<>();
 
    //需要session來對用戶發(fā)送數(shù)據(jù), 獲取連接特征userId
    private Session session;
    private Long userId;
   
    /**
     * @Title: onOpen
     * @Description: websocekt連接建立時的操作
     * @param @param userId 用戶id
     * @param @param session websocket連接的session屬性
     * @param @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("userId") Long userId,Session session) throws IOException{
        this.session = session;
        this.userId = userId;
        onlineCount++;
        //根據(jù)該用戶當(dāng)前是否已經(jīng)在別的終端登錄進(jìn)行添加操作
        if (userSocket.containsKey(this.userId)) {
            logger.debug("當(dāng)前用戶id:{}已有其他終端登錄",this.userId);
            userSocket.get(this.userId).add(this); //增加該用戶set中的連接實例
        }else {
            logger.debug("當(dāng)前用戶id:{}第一個終端登錄",this.userId);
            Set<WebsocketDemo> addUserSet = new HashSet<>();
            addUserSet.add(this);
            userSocket.put(this.userId, addUserSet);
        }
        logger.debug("用戶{}登錄的終端個數(shù)是為{}",userId,userSocket.get(this.userId).size());
        logger.debug("當(dāng)前在線用戶數(shù)為:{},所有終端個數(shù)為:{}",userSocket.size(),onlineCount);
    }
   
    /**
     * @Title: onClose
     * @Description: 連接關(guān)閉的操作
     */
    @OnClose
    public void onClose(){
        //移除當(dāng)前用戶終端登錄的websocket信息,如果該用戶的所有終端都下線了,則刪除該用戶的記錄
        if (userSocket.get(this.userId).size() == 0) {
            userSocket.remove(this.userId);
        }else{
            userSocket.get(this.userId).remove(this);
        }
        logger.debug("用戶{}登錄的終端個數(shù)是為{}",this.userId,userSocket.get(this.userId).size());
        logger.debug("當(dāng)前在線用戶數(shù)為:{},所有終端個數(shù)為:{}",userSocket.size(),onlineCount);
    }
   
    /**
     * @Title: onMessage
     * @Description: 收到消息后的操作
     * @param @param message 收到的消息
     * @param @param session 該連接的session屬性
     */
    @OnMessage
    public void onMessage(String message, Session session) {    
        logger.debug("收到來自用戶id為:{}的消息:{}",this.userId,message);
        if(session ==null)  logger.debug("session null");
    }
   
    /**
     * @Title: onError
     * @Description: 連接發(fā)生錯誤時候的操作
     * @param @param session 該連接的session
     * @param @param error 發(fā)生的錯誤
     */
    @OnError
    public void onError(Session session, Throwable error){
        logger.debug("用戶id為:{}的連接發(fā)送錯誤",this.userId);
        error.printStackTrace();
    }
   
  /**
   * @Title: sendMessageToUser
   * @Description: 發(fā)送消息給用戶下的所有終端
   * @param @param userId 用戶id
   * @param @param message 發(fā)送的消息
   * @param @return 發(fā)送成功返回true,反則返回false
   */
    public Boolean sendMessageToUser(Long userId,String message){
        if (userSocket.containsKey(userId)) {
            logger.debug(" 給用戶id為:{}的所有終端發(fā)送消息:{}",userId,message);
            for (WebsocketDemo WS : userSocket.get(userId)) {
                logger.debug("sessionId為:{}",WS.session.getId());
                try {
                    WS.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.debug(" 給用戶id為:{}發(fā)送消息失敗",userId);
                    return false;
                }
            }
            return true;
        }
        logger.debug("發(fā)送錯誤:當(dāng)前連接不包含id為:{}的用戶",userId);
        return false;
    }
  
}

Service層編寫

service層比較簡單,不多說,直接看代碼就行:

/** 
 * @Class: WebSocketMessageService
 * @Description:  使用webscoket連接向用戶發(fā)送信息
 * @author JFPZ
 * @date 2017年5月15日 上午20:17:01
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springside.modules.mapper.JsonMapper;
import com.hhxk.vrshop.entity.Message;
import com.hhxk.vrshop.web.webSocket.WebsocketDemo;
import com.hhxk.vrshop.web.webSocket.WebSocket;

@Service("webSocketMessageService")
public class WSMessageService {
    private Logger logger = LoggerFactory.getLogger(WSMessageService.class);
    //聲明websocket連接類
    private WebsocketDemo websocketDemo = new WebsocketDemo();

    /**
     * @Title: sendToAllTerminal
     * @Description: 調(diào)用websocket類給用戶下的所有終端發(fā)送消息
     * @param @param userId 用戶id
     * @param @param message 消息
     * @param @return 發(fā)送成功返回true,否則返回false
     */
    public Boolean sendToAllTerminal(Long userId,String message){   
        logger.debug("向用戶{}的消息:{}",userId,message);
        if(websocketDemo.sendMessageToUser(userId,message)){
            return true;
        }else{
            return false;
        }   
    }           
}

Controller層

Controller層也簡單,只需提供一個http請求的入口然后調(diào)用service即可,Controller層請求地址為:http://127.0.0.1:8080/your-project-name/message/TestWS

@Controller
@RequestMapping("/message")
public class MessageController extends BaseController{
    //websocket服務(wù)層調(diào)用類
    @Autowired
    private WSMessageService wsMessageService;

  //請求入口
    @RequestMapping(value="/TestWS",method=RequestMethod.GET)
    @ResponseBody
    public String TestWS(@RequestParam(value="userId",required=true) Long userId,
        @RequestParam(value="message",required=true) String message){
        logger.debug("收到發(fā)送請求,向用戶{}的消息:{}",userId,message);
        if(wsMessageService.sendToAllTerminal(userId, message)){
            return "發(fā)送成功";
        }else{
            return "發(fā)送失敗";
        }   
    }
}

前端連接代碼

html支持websocket,將下面代碼中的websocket地址中替換即可直接使用:

<!DOCTYPE html>
<html>

    <head lang="en">
        <meta charset="UTF-8">
        <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
        <link rel="stylesheet" >
        <link rel="stylesheet" >
        <script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
        <script src="http://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <title>webSocket-用戶66</title>
        <script type="text/javascript">
            $(function() {
                var websocket;
                if('WebSocket' in window) {
                                        console.log("此瀏覽器支持websocket");
                    websocket = new WebSocket("ws://127.0.0.1:8080/your-project-name/websocketDemo/66");
                } else if('MozWebSocket' in window) {
                    alert("此瀏覽器只支持MozWebSocket");
                } else {
                    alert("此瀏覽器只支持SockJS");
                }
                websocket.onopen = function(evnt) {
                    $("#tou").html("鏈接服務(wù)器成功!")
                };
                websocket.onmessage = function(evnt) {
                    $("#msg").html($("#msg").html() + "<br/>" + evnt.data);
                };
                websocket.onerror = function(evnt) {};
                websocket.onclose = function(evnt) {
                    $("#tou").html("與服務(wù)器斷開了鏈接!")
                }
                $('#send').bind('click', function() {
                    send();
                });

                function send() {
                    if(websocket != null) {
                        var message = document.getElementById('message').value;
                        websocket.send(message);
                    } else {
                        alert('未與服務(wù)器鏈接.');
                    }
                }
            });
        </script>
    </head>

    <body>
        <div class="page-header" id="tou">
            webSocket多終端聊天測試
        </div>
        <div class="well" id="msg"></div>
        <div class="col-lg">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="發(fā)送信息..." id="message">
                <span class="input-group-btn">
                    <button class="btn btn-default" type="button" id="send" >發(fā)送</button>
                </span>
            </div>
        </div>
    </body>

</html>

測試驗證

使用用戶id為66登錄2個終端,用戶id為88登錄1個終端,服務(wù)器中可以看到登錄的信息,如下圖所示:

用戶連接后臺websocket服務(wù)器

首先驗證用戶66的兩個終端接收是否能同時接收消息:


驗證用戶66的多終端接收消息

驗證用戶88接收消息:


驗證用戶88接收消息

總結(jié)

websocekt接口在mvc模式中被service層調(diào)用需要在@ServerEndpoint中添加configurator屬性,而實際情況需要根據(jù)業(yè)務(wù)需求來進(jìn)行設(shè)計。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容