nginx 서버 배치 websocket 프로젝트 연결 중단 오류: 연결 설정 오류: net:: ERRNAME_NOT_RESOLVED

8791 단어 nginx
프로젝트 는 팝 업 창 경고 가 필요 합 니 다. 원래는 coet4j 방식 으로 진행 되 었 으 나 나중에 tomcat 8.5 가 지원 되 지 않 는 다 는 것 을 알 게 되 었 습 니 다. 그래서 webSocket 방식 으로 실현 하려 고 합 니 다. webSocket 은 브 라 우 저 클 라 이언 트 와 서버 배경 에서 이 루어 진 전 쌍 공 통신 방식 으로 많은 웹 채 팅 도 구 는 이 방식 으로 진행 되 었 습 니 다.
로 컬 개발 시 정상적으로 사용 할 수 있 지만 nginx 프 록 시 서버 에 배치 되 었 을 때 오류 가 발생 하여 연결 되 지 않 습 니 다.
Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

나중에 nginx 서버 가 기본적으로 웹 소켓 을 열지 않 는 기능 을 발견 하 였 습 니 다. 이것 은 nginx 서버 에 설정 해 야 합 니 다.
 location /test/ {
                proxy_pass http://test.com;
                proxy_redirect default;
                proxy_set_header Upgrade $http_upgrade; # allow websockets
                proxy_set_header Connection "upgrade";
                proxy_http_version 1.1;
                }

또한 nginx 는 연결 시간 이 초과 되 거나 시간 이 초과 되 었 을 때 websocket 이 중단 되 는 것 을 설정 하 였 습 니 다. 그러면 socket 연결 을 유지 하고 끊 어 진 선 이 자동 으로 다시 연결 되 어야 합 니 다. 코드 는 다음 과 같 습 니 다.
웹 소켓 배경:
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

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.stereotype.Component;

import net.sf.json.JSONObject;


@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
	
	static Logger log=LoggerFactory.getLogger(WebSocketServer.class);
    //    ,           。            。
    private static int onlineCount = 0;
    //concurrent      Set,            MyWebSocket  。
    private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();

    //           ,              
    private Session session;

    //  sid
    private String sid="";
    /**
     *            */
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //  set 
        addOnlineCount();           //    1
        log.info("        :"+sid+",       " + getOnlineCount());
        this.sid=sid;
        try {
        	 sendMessage("    ");
        } catch (IOException e) {
            log.error("websocket IO  ");
        }
    }

    /**
     *          
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  // set   
        subOnlineCount();           //    1
        log.info("      !       " + getOnlineCount());
    }

    /**
     *              
     *
     * @param message           */
    @OnMessage
    public void onMessage(String message, Session session) {
    	log.info("      "+sid+"   :"+message);
        //    
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
            	log.error(e.toString());
                e.printStackTrace();
            }
        }
    }

	/**
	 * 
	 * @param session
	 * @param error
	 */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("    ");
        error.printStackTrace();
    }
	/**
	 *          
	 */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    
    /**
     *       
     * */
   public void sendMessage(Map dataMap)throws IOException{
	   try{if(dataMap!=null){
			JSONObject jsonObject = JSONObject.fromObject(dataMap);
			StringBuilder builder = new StringBuilder(jsonObject.toString());		
			//       
			this.session.getBasicRemote().sendText(builder.toString());
			log.info("    ");
			}	
	   }catch(Exception e) {
		   log.error(e.toString());
	   }
   }
    /**
     *        
     * */
    public static void sendInfo(String message, String sid) throws IOException {
    	log.info("       "+sid+",    :"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
            	//            sid , null     
            	if(sid==null) {
            		item.sendMessage(message);
            	}else if(item.sid.equals(sid)){
            		item.sendMessage(message);
            	}
            } catch (IOException e) {
            	log.error(e.toString());
                continue;
            }
        }
    }
    /**
     *        
     * */
    public static void sendInfoMap(Map dataMap, String sid) throws IOException {
    	log.info("       "+sid+",    :"+dataMap.toString());
        for (WebSocketServer item : webSocketSet) {
            try {
            	item.sendMessage(dataMap);
            	//            sid , null           
            	/*if(sid==null) {
            		item.sendMessage(dataMap);
            	}else if(item.sid.equals(sid)){
            		item.sendMessage(dataMap);
            	}*/
            } catch (IOException e) {
            	log.error(e.toString());
                continue;
            }
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

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

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



프론트 페이지 및 js:
var websocket_connected_count = 0;
var onclose_connected_count = 0;
/**websocekt*/
function webSocketClient(){
	var socket;  
	if(typeof(WebSocket) == "undefined") {  
	    console.log("        WebSocket");  
	}else{  
	    console.log("       WebSocket");  
	    	//httprequest  id
	    	var sid = "";
	    	//   WebSocket  ,                      
	        socket =new WebSocket("ws://127.0.0.1:8080/butlerBf/websocket/"+sid);   
	        //      
	        socket.onopen = function() {  
	            console.log("Socket    "); 
	            //socket.send("          " + location.href + new Date());  
	        };  
	        //        
	        socket.onmessage = function(msg) {  
	            if(msg.data!="       WebSocket"&&msg.data!="Socket    "&&msg.data!="    "&&msg.data!="ping"&&msg.data!=""){
	            	console.log(msg);
	            	checkAuthority(msg.data);
	            	heartCheck.reset().start();
	            }
	        };  
	        //      
	        socket.onclose = function(e) {  
	            console.log("Socket   "); 
	            console.log(e);
	        };
	        //         
	        socket.onerror = function() {  
	        	websocket_connected_count++;
	            if(websocket_connected_count <= 5){
	            	webSocketClient()
	            }
	            console.log("Socket     ");  
	            //          
	        }  
	        //     ,  socket
	        //jquery1.8      ,3.0     
	         $(window).unload(function(){  
	             socket.close();  
	         });  
	}
	//     ,             ,       ,  server       ,   server            ,       ,    。
    var heartCheck = {
        timeout: 60000,        // 60s     , server             ,                      。
        serverTimeoutObj: null,
        reset: function(){
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function(){
            var self = this;
            this.serverTimeoutObj = setInterval(function(){
                if(socket.readyState == 1){
                    console.log("    ,        ");
                    socket.send("ping");
                    heartCheck.reset().start();    //        ,        ,      
                }else{
                    console.log("    ,    ");
                    webSocketClient();
                }
            }, this.timeout)
        }
    }

}

또한, nginx 가 다음 과 같은 읽 기 시간 초과 시간 을 설정 하지 않 으 면 websocket 은 계속 끊 기 고 다시 연결 되 며 메모리 가 소모 되 므 로 길 게 설정 하 는 것 을 권장 합 니 다.
location /test{
            root html;
	    proxy_pass  http://test.com;
	    proxy_set_header Upgrade $http_upgrade; # allow websockets
    	proxy_set_header Connection "upgrade";
    	proxy_http_version 1.1;
        proxy_connect_timeout 60s;#l      ,             
	    proxy_read_timeout 500s;#     
	    proxy_send_timeout 500s;#     
            index  index.html index.htm;
        }

좋은 웹페이지 즐겨찾기