JAVA後端實現WebSocket消息推送(實現推送給某一個指定用戶)

注意:websocket只有tomcat7.4.5以上才支持

可以用google插件來測試

所需要jar包

<!--websocket-->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
			<scope>provided</scope>
		</dependency>

session隊列:

package com.common.pojo.websocket;

import lombok.Data;

import javax.websocket.Session;
import java.io.Serializable;

/**
 * websocketsession實體類
 *
 * @author nachuan
 * @create 2019-09-06 10:21
 */
@Data

public class WebsocketSessionDto implements Serializable {

    /**sessionid*/
    private String sessionId;
    /**websocket的session*/
    private Session session;
    /**用戶id*/
    private String userId;
    /**心跳時間*/
    private long heartbeatTime;
    /**組id*/
    private String groupId;
    /**最後鏈接時間*/
    private long lastConTime;
}

 任務隊列

package com.common.pojo.websocket;

import lombok.Data;
import org.junit.Test;

import java.io.Serializable;

/**
 * websocket返回值
 *
 * @author nachuan
 * @create 2019-09-16 14:50
 */
@Data
public class ResWsTask implements Serializable {

    /**type默認0 普通消息   1,心跳*/
    private int  methodType = 0;
    /**返回結果 */
    private WebSocketTask task;


}




package com.common.pojo.websocket;

import com.common.utils.jsonUtils.MyFastJsonUtils;
import com.common.utils.randomutils.MyUUIDutils;
import com.skyvis.websocket.ResWsTask;
import lombok.Data;

import java.io.Serializable;

/**
 * websocket失敗任務
 *
 * @author nachuan
 * @create 2019-09-06 13:29
 */
@Data
public class WebSocketTask implements Serializable {

    /**任務id*/
    private String taskId;
    /**消息*/
    private String msg;
    /**發送時間*/
    private long startTime;
    /**用戶id*/
    private String userId;
    /**組id*/
    private String groupId;

    /**任務編號*/
    private Integer taskNum;


    public static void main(String[] args) {

        ResWsTask resWsTask = new ResWsTask();
//        resWsTask.setType(0);
        WebSocketTask task = new WebSocketTask();
        task.setTaskId(MyUUIDutils.getTimeUuid());
        task.setMsg("測試消息");
        task.setStartTime(System.currentTimeMillis());
        task.setUserId(MyUUIDutils.getTimeUuid());
        task.setGroupId(MyUUIDutils.getTimeUuid());
        task.setTaskNum(100001);
        resWsTask.setTask(task);

        System.out.println(MyFastJsonUtils.obj2JsonStr(resWsTask));
    }


}

websocket服務(單機版): 



import com.common.pojo.websocket.WebSocketTask;
import com.common.pojo.websocket.WebsocketSessionDto;
import com.common.utils.dailyutils.EmptyUtils;
import com.common.utils.jsonUtils.MyFastJsonUtils;
import com.common.utils.log.MyLogUtils;
import com.common.utils.randomutils.MyUUIDutils;
import com.common.utils.timeUtils.MyTimeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;

/**
 * websocket多連
 *
 * @author nachuan
 * @create 2019-09-08 15:15
 */



@ServerEndpoint("/webSocketService/{uid}")
@Component
public class MyWebSocketMore implements Serializable {
    private static final Logger log = MyLogUtils.getSlf4jLogger(MyWebSocketMore.class);


    /**session存儲集合*/
    private  static List<WebsocketSessionDto> sessionList = new ArrayList<WebsocketSessionDto>();

    /**任務隊列*/
    private static List<WebSocketTask> taskList = new ArrayList<WebSocketTask>();

    /**每個session訪問的次數*/
    private static HashMap<String, Integer> sessionUserInCountMap = new HashMap<>();



    @Scheduled(cron = "*/30 * * * * ?")
    public void updateData(){
        log.info("清理sessionList詳情:{}",sessionList);
        if (EmptyUtils.isNotEmpty(sessionList)) {
            for (int i = 0; i < sessionList.size(); i++) {
                if (!sessionList.get(i).getSession().isOpen()) {
                    removeSession(sessionList.get(i).getSession());
                    log.info("清理無用的session ,sessionId={},userId={}",sessionList.get(i).getSessionId(),sessionList.get(i).getUserId());
                }
            }
        }

    }

    @Scheduled(cron = "*/5 * * * * ?")
    public void sendTask(){

        if (EmptyUtils.isNotEmpty(taskList)) {
            for (int i = 0; i < taskList.size(); i++) {
                WebSocketTask task = taskList.get(i);
                log.info("隊列任務====開始發送-接收人:{},消息:{},任務時間={},taskId={}",task.getUserId(),task.getMsg(), MyTimeUtils.fmttime(task.getStartTime()),task.getTaskId());
                for (WebsocketSessionDto websocketSessionDto : sessionList) {
                    if (Objects.equals(task.getUserId(), websocketSessionDto.getUserId())) {
                        try {
                            boolean isOpen = websocketSessionDto.getSession().isOpen();
                            if (isOpen) {
                                websocketSessionDto.getSession().getBasicRemote().sendText(MyFastJsonUtils.obj2JsonStr(task));
                                log.info("隊列任務-正在發送====開始發送-接收人:{},消息:{},任務時間={},taskId={}",task.getUserId(),task.getMsg(), MyTimeUtils.fmttime(task.getStartTime()),task.getTaskId());
                            }


                        } catch (IOException e) {
                            log.info("隊列任務=====失敗任務數量:{},任務內容:{}",taskList.size(),taskList);
                            e.printStackTrace();
                            throw new RuntimeException(e);

                        }

                    }
                }
            }
        }
    }

    @OnOpen
    public void onOpen (Session session, @PathParam(value = "uid")String uid )   {
        log.info("建立鏈接:sessinid={},userid={},sessionList={},sessionList.size={},groupId={}" ,
                session.getId(), uid,sessionList.toString(),sessionList.size());
                addWebSocketSession(session, uid);

        log.info("建立鏈接後:sessionList.size={},詳情={}" ,sessionList.size(), sessionList);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("斷開連接的sessionid ={} " , session.getId());

        removeSession(session);

    }

    /**
     * 移除無用的session
     * @param session
     */
    private void removeSession(Session session)   {

        if (EmptyUtils.isNotEmpty(sessionList)) {
            for (int i = 0; i < sessionList.size(); i++) {
                if (Objects.equals(session.getId(), sessionList.get(i).getSessionId())) {
                    sessionList.remove(sessionList.get(i));
                    log.info("移除session後sessionid={}",session.getId());
                    log.info("移除後的sessionList.size={},sessionList={}",sessionList.size(),sessionList);
                    try {
                        session.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }


    /**
     * 發送消息給某個人
     * @param userId
     * @param msg
     */
    public void  sendMsgTosb(String userId,String groupId,Integer taskNum ,String msg)   {
        WebSocketTask task = new WebSocketTask();
        task.setMsg(msg);
        task.setTaskId(MyUUIDutils.getTimeUuid());
        task.setStartTime(System.currentTimeMillis());
        task.setUserId(userId);
        task.setGroupId(groupId);
        task.setTaskNum(taskNum);
        log.info("開始發送-接收人:{},消息:{}",userId,msg);
        Map<String,Object> userMsgMap = new HashMap<>();

        for (WebsocketSessionDto websocketSessionDto : sessionList) {
//            if (Objects.equals(userId, websocketSessionDto.getUserId()) && websocketSessionDto.getSession().isOpen() && !Objects.equals(userMsgMap.get(userId),msg)) {
            if (Objects.equals(userId, websocketSessionDto.getUserId()) && websocketSessionDto.getSession().isOpen() ) {
                try {
                    //如果不包含
                    websocketSessionDto.getSession().getBasicRemote().sendText(MyFastJsonUtils.obj2JsonStr(task));
//                    userMsgMap.put(userId,msg);
                    log.info("發送成功------接收人:{},消息:{}",userId,msg);
                } catch (IOException e) {
                    e.printStackTrace();

                    log.info("失敗任務數量:{},任務內容:{}",taskList.size(),taskList);
                }
                taskList.add(task);
            }else {
                continue;
            }
        }
    }
    @OnMessage
    public void onMessage(String message,Session session)   {
        log.info("收到消息: msg={},sessionid={},sessionSize={},sessionList詳情={}" ,message,session.getId(),sessionList.size(),sessionList);

        String uid= "";
        String taskId = "";
        if (message.contains("userId") && message.contains("taskId")) {
            Map<Object, Object> map = MyFastJsonUtils.strToMap(message);
            uid = (String) map.get("userId");
            taskId = (String) map.get("taskId");
        }


        int j  = 0;
        if (EmptyUtils.isNotEmpty(sessionList)) {
            for (int i = 0; i < sessionList.size(); i++) {

                //如果有這個session ,需要把這個session心跳更新
                if (Objects.equals(sessionList.get(i).getSessionId(), session.getId())) {
                    sessionList.get(i).setHeartbeatTime(System.currentTimeMillis());
                }

                if (Objects.equals(sessionList.get(i).getUserId(), uid) && Objects.equals(sessionList.get(i).getSessionId(),session.getId())) {
                    j = 1;
                }

            }
        }
        //如果session集合不包含此userid需要添加
        if (j == 0) {
            addWebSocketSession(session,uid);
            log.info("剛開始連接失敗,把session加入集合,userid={}",uid );

        }


        //如果返回了任務id證明任務執行成功,需要移除任務
        if (EmptyUtils.isNotEmpty(taskList)) {
            for (int i = 0; i < taskList.size(); i++) {
                if (Objects.equals(taskList.get(i).getTaskId(), taskId)) {
                    taskList.remove(taskList.get(i));

                }
            }
        }




    }

    /**
     * 添加websocketsession
     * @param session
     * @param uid
     */
    private void addWebSocketSession(Session session, String uid ) {
        log.info("開始添加sessionid={},uid={}",session.getId(),uid);


        if (StringUtils.isNotBlank(uid)  && !Objects.equals(uid,"null")) {
            log.info("正在添加uid爲{}的session",uid);
            WebsocketSessionDto websocketSessionDto = new WebsocketSessionDto();
            websocketSessionDto.setSession(session);
            websocketSessionDto.setSessionId(session.getId());
            websocketSessionDto.setUserId(uid);
            websocketSessionDto.setHeartbeatTime(System.currentTimeMillis());
            websocketSessionDto.setLastConTime(System.currentTimeMillis());
            sessionList.add(websocketSessionDto);
            log.info("websocketSessionDto詳情={},當前時間={}",websocketSessionDto,System.currentTimeMillis());
        }else {
            log.warn("userid爲空,uid={}",uid);
        }

    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.warn(error.getMessage());
        log.warn("發生錯誤的sessionid = " + session.getId());
        removeSession(session);
    }

}

websocket服務,集羣版

(websocket無法注入redisTemple所引用的redis工具類:https://nachuan.blog.csdn.net/article/details/96644466

map排序工具類: https://nachuan.blog.csdn.net/article/details/100898502



import com.common.pojo.websocket.ResWsTask;
import com.common.pojo.websocket.WebSocketTask;
import com.common.pojo.websocket.WebsocketSessionDto;
import com.common.utils.dailyutils.EmptyUtils;
import com.common.utils.jsonUtils.MyFastJsonUtils;
import com.common.utils.log.MyLogUtils;
import com.common.utils.map.JavaMapUtils;
import com.common.utils.otherUtils.RedisAPI;
import com.common.utils.timeUtils.MyTimeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * websocket多連
 *
 * @author nachuan
 * @create 2019-09-08 15:15
 */



@ServerEndpoint("/webSocketService/{uid}")
@Component
public class MyWebSocketMore implements Serializable {
    private static final Logger log = MyLogUtils.getSlf4jLogger(MyWebSocketMore.class);


    /**session存儲集合*/
    private  static final List<WebsocketSessionDto> sessionList = new ArrayList<WebsocketSessionDto>();

    /**任務key*/
    private static final String taskKey = "websocketTaskKey";

    /**每個session訪問的次數*/
    private static HashMap<String, Integer> sessionUserInCountMap = new HashMap<>();
    /**避免併發情況下,一個session同時被佔用發送消息*/
    private static   final Lock lock = new ReentrantLock();
 

    @Scheduled(cron = "*/30 * * * * ?")
    public void updateData(){
//        log.info("清理sessionList詳情:{}",sessionList);
        if (EmptyUtils.isNotEmpty(sessionList)) {
            for (int i = 0; i < sessionList.size(); i++) {
                if (!sessionList.get(i).getSession().isOpen()) {
                    removeSession(sessionList.get(i).getSession());
//                    log.info("清理無用的session ,sessionId={},userId={}",sessionList.get(i).getSessionId(),sessionList.get(i).getUserId());
                }
            }
        }

    }

    @Scheduled(cron = "*/10 * * * * ?")
    public void sendTask(){

        Jedis jedis = RedisAPI.getJedis();
        jedis.select(MyWebSocketEnum.WS_SELECT_DATABASE);

        Map<String, String> valueMap = jedis.hgetAll(taskKey);
        if (EmptyUtils.isNotEmpty(valueMap.values())) {
            Map<String, String> resultMap = JavaMapUtils.sortMap(valueMap);

            Collection<String> taskCollection = resultMap.values();

            Object[] taskList =  taskCollection.toArray();
            if (EmptyUtils.isNotEmpty(taskList)) {
                for (int i = 0; i < taskList.length; i++) {
                    ResWsTask resWsTask = MyFastJsonUtils.strToBean(taskList[i].toString(), ResWsTask.class);
                    WebSocketTask task = resWsTask.getTask();
                    //超過24小時的任務直接刪除
                    log.info("任務時間差:{},任務id={}",System.currentTimeMillis() - task.getStartTime(),task.getTaskId());
                    if (System.currentTimeMillis() - task.getStartTime() > 24 * 60 * 60 * 1000) {
                        jedis.hdel(taskKey,task.getTaskId());
                    }
                    log.info("隊列任務====開始發送-接收人:{},消息:{},任務時間={},taskId={}",task.getUserId(),task.getMsg(), MyTimeUtils.fmttime(task.getStartTime()),task.getTaskId());
                    for (WebsocketSessionDto websocketSessionDto : sessionList) {
                        if (Objects.equals(task.getUserId(), websocketSessionDto.getUserId())) {
                            try {
                                Session session = websocketSessionDto.getSession();
                                sendWsText(session,resWsTask);
                                    log.info("隊列任務-正在發送====開始發送-接收人:{},消息:{},任務時間={},taskId={}",task.getUserId(),task.getMsg(), MyTimeUtils.fmttime(task.getStartTime()),task.getTaskId());
                            } catch (IOException e) {
                                log.info("隊列任務=====失敗任務數量:{},任務內容:{}",taskList.length,taskList);
                                e.printStackTrace();
                                throw new RuntimeException(e);

                            }

                        }
                    }
                }
            }
        }
        jedis.close();
    }

    /**
     * 發送websocket消息
     * @param session
     * @param resWsTask
     * @throws IOException
     */
    private  void sendWsText(Session  session,ResWsTask  resWsTask) throws IOException {

        lock.lock();
        if (session.isOpen()) {
                session.getBasicRemote().sendText(MyFastJsonUtils.obj2JsonStr(resWsTask));

            }

        lock.unlock();
    }

    @OnOpen
    public void onOpen (Session session, @PathParam(value = "uid")String uid )   {
        log.info("建立鏈接:sessinid={},userid={},sessionList={},sessionList.size={},groupId={}" ,
                session.getId(), uid,sessionList.toString(),sessionList.size());
        addWebSocketSession(session, uid);

        log.info("建立鏈接後:sessionList.size={},詳情={}" ,sessionList.size(), sessionList);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("斷開連接的sessionid ={} " , session.getId());

        removeSession(session);

    }

    /**
     * 移除無用的session
     * @param session
     */
    private void removeSession(Session session)   {

        if (EmptyUtils.isNotEmpty(sessionList)) {
            for (int i = 0; i < sessionList.size(); i++) {
                if (Objects.equals(session.getId(), sessionList.get(i).getSessionId())) {
                    sessionList.remove(sessionList.get(i));
                    log.info("移除session後sessionid={}",session.getId());
                    log.info("移除後的sessionList.size={},sessionList={}",sessionList.size(),sessionList);
                    try {
                        session.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }


    /**
     * 發送消息給某個人
     * @param userId
     * @param msg
     */
    public void  sendMsgTosb(String userId,String groupId,Integer taskNum ,String msg)   {
        WebSocketTask task = new WebSocketTask();
        ResWsTask resWsTask = new ResWsTask();
        task.setMsg(msg);
        task.setTaskId(System.currentTimeMillis()+"");
        task.setStartTime(System.currentTimeMillis());
        task.setUserId(userId);
        task.setGroupId(groupId);
        task.setTaskNum(taskNum);
        Jedis jedis = RedisAPI.getJedis();
        jedis.select(MyWebSocketEnum.WS_SELECT_DATABASE);
        log.info("開始發送-接收人:{},消息:{}",userId,msg);

        resWsTask.setTask(task);
        getSessionAndSendMsg(userId, msg, resWsTask, jedis);
        jedis.close();
    }

    /**
     * 獲取session併發送消息
     * @param userId
     * @param msg
     * @param task
     * @param jedis
     */
    private void getSessionAndSendMsg(String userId, String msg, ResWsTask task, Jedis jedis) {
        for (WebsocketSessionDto websocketSessionDto : sessionList) {
            if (Objects.equals(userId, websocketSessionDto.getUserId()) && websocketSessionDto.getSession().isOpen()) {
                try {
                    //如果不包含
                    Session session = websocketSessionDto.getSession();
                    sendWsText(session,task);
                    log.info("發送成功------接收人:{},消息:{}", userId, msg);
                } catch (IOException e) {
                    e.printStackTrace();

                    log.info("失敗任務數,任務內容:{}", task);
                }
                jedis.hset(taskKey, task.getTask().getTaskId(), MyFastJsonUtils.obj2JsonStr(task));

            } else {
                continue;
            }
        }
    }

    /**
     * 發送消息給某羣組
     * @param userIdList  接受人的id集合
     * @param groupId 組id
     * @param taskNum 任務編號
     * @param msg 消息
     */
    public void  sendMsgToGroup(List<String>userIdList, String groupId,Integer taskNum ,String msg)   {
        Jedis jedis = RedisAPI.getJedis();
        jedis.select(MyWebSocketEnum.WS_SELECT_DATABASE);
        for (String userId : userIdList) {
            ResWsTask resWsTask = new ResWsTask();
            WebSocketTask task = new WebSocketTask();
            task.setMsg(msg);
            task.setTaskId(System.currentTimeMillis()+"");
            task.setStartTime(System.currentTimeMillis());
            task.setUserId(userId);
            task.setGroupId(groupId);
            task.setTaskNum(taskNum);
            resWsTask.setTask(task);
            log.info("開始發送-接收人:{},消息:{}",userId,msg);


            getSessionAndSendMsg(userId, msg, resWsTask, jedis);
        }
        jedis.close();

    }
    @OnMessage
    public void onMessage(String message,Session session)   {
//        log.info("收到消息: msg={},sessionid={},sessionSize={},sessionList詳情={}" ,message,session.getId(),sessionList.size(),sessionList);

        Jedis jedis = RedisAPI.getJedis();
        jedis.select(MyWebSocketEnum.WS_SELECT_DATABASE);
        String uid= "";
        String taskId = "";
        if (message.contains("userId") && message.contains("taskId")) {
            Map<Object, Object> map = MyFastJsonUtils.strToMap(message);
            uid = (String) map.get("userId");
            taskId = (String) map.get("taskId");
        }


        int j  = 0;
        if (EmptyUtils.isNotEmpty(sessionList)) {
            for (int i = 0; i < sessionList.size(); i++) {

                //如果有這個session ,需要把這個session心跳更新
                if (Objects.equals(sessionList.get(i).getSessionId(), session.getId())) {
                    sessionList.get(i).setHeartbeatTime(System.currentTimeMillis());
                    try {
                        if (sessionList.get(i).getSession().isOpen()) {
                            ResWsTask resWsTask = new ResWsTask();

//                            1是心跳
                            resWsTask.setMethodType(1);
                            Session session1 = sessionList.get(i).getSession();
                            sendWsText(session1,resWsTask);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (Objects.equals(sessionList.get(i).getUserId(), uid) && Objects.equals(sessionList.get(i).getSessionId(),session.getId())) {
                    j = 1;
                }

            }
        }
        //如果session集合不包含此userid需要添加
        if (j == 0) {
            addWebSocketSession(session,uid);
            log.info("剛開始連接失敗,把session加入集合,userid={}",uid );

        }


        //如果返回了任務id證明任務執行成功,需要移除任務
        jedis.hdel(taskKey,taskId);
        jedis.close();

    }

    /**
     * 添加websocketsession
     * @param session
     * @param uid
     */
    private void addWebSocketSession(Session session, String uid ) {
        log.info("開始添加sessionid={},uid={}",session.getId(),uid);


        if (StringUtils.isNotBlank(uid)  && !Objects.equals(uid,"null")) {
//            log.info("正在添加uid爲{}的session",uid);
            WebsocketSessionDto websocketSessionDto = new WebsocketSessionDto();
            websocketSessionDto.setSession(session);
            websocketSessionDto.setSessionId(session.getId());
            websocketSessionDto.setUserId(uid);
            websocketSessionDto.setHeartbeatTime(System.currentTimeMillis());
            websocketSessionDto.setLastConTime(System.currentTimeMillis());
            sessionList.add(websocketSessionDto);
//            log.info("websocketSessionDto詳情={},當前時間={}",websocketSessionDto,System.currentTimeMillis());
        }else {
            log.warn("userid爲空,uid={}",uid);
        }

    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.warn(error.getMessage());
        log.warn("發生錯誤的sessionid = " + session.getId());
        removeSession(session);
    }




}

前端頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

Welcome<br/>
<input id="text" type="text"/>
<button onclick="send()">發送消息</button>
<hr/>
<button onclick="closeWebSocket()">關閉WebSocket連接</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">

    function getRootPath(){
        //獲取當前網址,如: http://localhost:8083/uimcardprj/share/meun.jsp
        var curWwwPath=window.document.location.href;
        //獲取主機地址之後的目錄,如: uimcardprj/share/meun.jsp
        var pathName=window.document.location.pathname;
        var pos=curWwwPath.indexOf(pathName);
        //獲取主機地址,如: http://localhost:8083
        var localhostPaht=curWwwPath.substring(0,pos);
        //獲取帶"/"的項目名,如:/uimcardprj
        var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
        return(localhostPaht+projectName);
    }
    var userId = '20190916193822782474f8718c537fefc1f0';
    var websocket = null;
    var url = getRootPath();

    var subStrNum = 0;
    if (url.indexOf("https://") != -1) {
        subStrNum = 8;
    }else {
        subStrNum = 7;
    }
    var wsurl = url.substr(subStrNum);;
    console.log("wsurl",wsurl);
    var websocketUrl = "ws://" + wsurl +"/webSocketService/"+ userId;
    //判斷當前瀏覽器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket(websocketUrl);
    }
    else {
        alert('當前瀏覽器 Not support websocket');
    }
    var online_send = setInterval(getWebSocketStatus, 3000);

    function getWebSocketStatus() {
        console.log("wsurl",wsurl);

        console.log("定時器開始:檢查");
        console.log("結果:" + websocket.readyState);
        console.log("WebSocket.OPEN:" + WebSocket.OPEN);
        console.log("WebSocket.CONNECTING:" + WebSocket.CONNECTING);
        if (websocket.readyState != WebSocket.OPEN  && websocket.readyState != WebSocket.CONNECTING) {
            console.log("不滿足條件");
            websocket = new WebSocket(websocketUrl);
        }else {
            console.log("滿足條件,發送消息");
            var obj = new Object();
            obj.userId=userId;
            obj.taskId="";
            websocket.send(JSON.stringify(obj));

        }

    }


    //連接發生錯誤的回調方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket連接發生錯誤");
    };

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

    //接收到消息的回調方法
    websocket.onmessage = function (event) {

        console.log("收到消息:",event);
        console.log("收到消息詳情:",event.data);

        setMessageInnerHTML(event.data);
    }

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

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

    //將消息顯示在網頁上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

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

    //發送消息
    function send() {
        var message = document.getElementById('text').value;
        console.log('websocket'+websocket);
        console.log("message:" + message);

        var obj = new Object();
        obj.userId=userId;
        obj.taskId=message;
        websocket.send(JSON.stringify(obj));
    }
</script>

</html>

如果是nginx反向代理:

                        #websocket支持
                        proxy_set_header Upgrade $http_upgrade;
                         proxy_set_header Connection "upgrade";

 nginx配置後效果圖

demo

 

function getRootPath(){
    //獲取當前網址,如: http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //獲取主機地址之後的目錄,如: uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //獲取主機地址,如: http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //獲取帶"/"的項目名,如:/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);
}

//------------------websocket 開始-------

var websocket = null;
var url = getRootPath();

var subStrNum = 0;
if (url.indexOf("https://") != -1) {
    subStrNum = 8;
}else {
    subStrNum = 7;
}
var wsurl = url.substr(subStrNum);

var websocketUrl = null;
//判斷當前瀏覽器是否支持WebSocket


var online_send = setInterval(getWebSocketStatus, 10000);
    setTimeout(getWebsocket,500);
    setTimeout(getWebSocketStatus,1000);
function getWebsocket() {

    websocketUrl = "ws://" + wsurl +"/webSocketService/"+ userId;
    if ('WebSocket' in window) {
        websocket = new WebSocket(websocketUrl);
    }
    else {
        alert('當前瀏覽器不支持此訪問,請更換谷歌瀏覽器訪問');
    }

    //連接發生錯誤的回調方法
    websocket.onerror = function () {
        te("網絡異常,請檢查網絡...");
    };

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

//接收到消息的回調方法
    websocket.onmessage = function (event) {

        console.log("收到消息:",event);
        console.log("收到消息詳情:",event.data);


        var taskInfo = JSON.parse(event.data);

        var methodType = taskInfo.methodType;
        if (methodType == 1) {
            return;
        }
        var taskMsg = taskInfo.task.msg;
        var taskNum = taskInfo.task.taskNum;
        var taskId = taskInfo.task.taskId;


        //如果是100001或者100002是上傳或者下載
        if(taskNum == 100001  || taskNum == 100002){
            getIsHaveNewEvidence(taskId,taskNum,taskMsg);
        }
    }

//連接關閉的回調方法
    websocket.onclose = function () {
    }

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

    if (websocket.readyState != WebSocket.OPEN  && websocket.readyState != WebSocket.CONNECTING) {
        console.log("不滿足條件");
        websocket = new WebSocket(websocketUrl);
    }else {
        console.log("滿足條件,發送消息");

        sendWebsocketMsg(userId,"")
    }

}

/**
 * 發送websocket信息
 */
function sendWebsocketMsg(userId,taskId){
    var obj = new Object();
    obj.userId=userId;
    obj.taskId=taskId;
    if (websocket.readyState == WebSocket.OPEN) {
        websocket.send(JSON.stringify(obj));

    }else  if (websocket.readyState == WebSocket.CONNECTING) {
        setTimeout(sendWebsocketMsg(userId,taskId),3000)
    }





}

 

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