Websocket如何實現長連接

實現長連接

由於websocket連接成功過段時間自動關閉,無法繼續獲取消息
於是我就想到一個辦法,就是自動關閉時再重新創建一次(因爲自動關閉也不是很快就關閉的,所以我就這麼寫),雖然實現方式不是很好,但是也暫時的實現了長連接方式
前端JS

		var websocket = null;
		var host = document.location.host;
		var username = "1001"; // 獲得當前登錄人員的userName --這裏使用當前項目ID做判斷
		var judgeTemp = 0;
		// alert(username)
		createWebSorket();
		function createWebSorket(){
			//判斷當前瀏覽器是否支持WebSocket 
			if('WebSocket' in window) {
				websocket = new WebSocket('ws://' + host + '/Project/webSocket/' + username);
				initEventHandle();
			} else {
				alert('當前瀏覽器 Not support websocket,消息推送將無法使用')
			}
		}
		function initEventHandle(){
			//連接發生錯誤的回調方法 
			websocket.onerror = function() {
				judgeTemp = 1;
				//這裏就是你要顯示的信息的函數(自定義)
				setMessageInnerHTML("WebSocket消息推送連接發生錯誤",1);
			};
			
			//連接成功建立的回調方法 
			websocket.onopen = function() {
			//這裏就是你要顯示的信息的函數(自定義)
				setMessageInnerHTML("WebSocket消息推送連接成功",1);
				console.log("成功連接---"+judgeTemp)
			}
			
			//接收到消息的回調方法 
			websocket.onmessage = function(event) {
			//這裏就是你要顯示的信息的函數(自定義)
				setMessageInnerHTML(event.data);
			}
			
			//連接關閉的回調方法 
			websocket.onclose = function() {
				console.log("關閉連接---"+judgeTemp)
				if(judgeTemp == 1){
				//這裏就是你要顯示的信息的函數(自定義)
					setMessageInnerHTML("WebSocket消息推送連接關閉",1);
				}else{
					createWebSorket();
				}
			}
			//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。 
			window.onbeforeunload = function() {
				judgeTemp = 1;
				closeWebSocket();
			}
		}
		//關閉WebSocket連接 
		function closeWebSocket() {
			websocket.close();
		}

後端實現
我這裏是用SSH的框架(其實也沒啥區別的)

package com.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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 net.sf.json.JSONObject;

@ServerEndpoint("/webSocket/{username}")  
public class WebSocket { 
        private static int onlineCount = 0; 
       // private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>(); 
        private static List<Map<String, WebSocket>> clients = null;
        private Session session; 
        private String username; 
       
        @OnOpen 
        public void onOpen(@PathParam("username") String username, Session session) throws IOException { 
       
            this.username = username; 
            this.session = session; 
               
            //爲了實現多個頁面登錄同一個賬號時,同時推送全部頁面
            if(clients == null) {
            	synchronized (WebSocket.class) {
					if(clients == null) {
						clients = new ArrayList<Map<String, WebSocket>>();
					}
				}
            }
            addOnlineCount();
            Map<String, WebSocket> clien = new ConcurrentHashMap<String, WebSocket>(); 
            clien.put(username, this);
            clients.add(clien);
            //clients.put(username, this);
            //System.out.println("已連接");
        } 
       
        @OnClose 
        public void onClose() throws IOException { 
        	for(int i=0; i< clients.size(); i++) {
        		Map<String, WebSocket> clien = clients.get(i);
        		for (WebSocket item : clien.values()) { 
        			if(item.session.equals(session))
            			clients.remove(i);
        		}
        	}
            //clients.remove(username); 
            subOnlineCount(); 
        } 
       
        @OnMessage 
        public void onMessage(String message) throws IOException { 
       
            JSONObject jsonTo = JSONObject.fromObject(message); 
            String mes = (String) jsonTo.get("message");
             
            if (!jsonTo.get("To").equals("All")){ 
                sendMessageTo(mes, jsonTo.get("To").toString()); 
            }else{ 
                sendMessageAll(mes); 
            } 
        } 
       
        @OnError 
        public void onError(Session session, Throwable error) { 
            error.printStackTrace(); 
        } 
       
        public void sendMessageTo(String message, String To) throws IOException { 
            // session.getBasicRemote().sendText(message); 
            //session.getAsyncRemote().sendText(message); 
            /*for (WebSocket item : clients.values()) { 
                if (item.username.equals(To) ) 
                    item.session.getAsyncRemote().sendText(message); 
            } */
        	for(int i=0; i< clients.size(); i++) {
        		Map<String, WebSocket> clien = clients.get(i);
        		for (WebSocket item : clien.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); 
            } */
        	for(int i=0; i< clients.size(); i++) {
        		Map<String, WebSocket> clien = clients.get(i);
        		for (WebSocket item : clien.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 static synchronized List<Map<String, WebSocket>> getClients() { 
            return clients; 
        } 
        
        
        
        
}

備註
如果遇到無法找到問題
通道:https://blog.csdn.net/weixin_43992507/article/details/103256233

nginx下無法連接websocket
通道:https://blog.csdn.net/weixin_43992507/article/details/103337106

發佈了41 篇原創文章 · 獲贊 14 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章