nginx 서버 배치 websocket 프로젝트 연결 중단 오류: 연결 설정 오류: net:: ERRNAME_NOT_RESOLVED
8791 단어 nginx
로 컬 개발 시 정상적으로 사용 할 수 있 지만 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;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
간단! Certbot을 사용하여 웹 사이트를 SSL(HTTPS)화하는 방법초보자가 인프라 주위를 정돈하는 것은 매우 어렵습니다. 이번은 사이트를 간단하게 SSL화(HTTP에서 HTTPS통신)로 변경하는 방법을 소개합니다! 이번에는 소프트웨어 시스템 Nginx CentOS7 의 환경에서 S...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.