NodeJS

2016-12-16 1 views
0
내가 아래로 NodeJS로 작성된 간단한 작업 웹 서버가

사용하여 파일 변경 config (설정) 할 때 웹 서버를 다시 시작 :NodeJS

var http = require("http"); 
var fs = require("fs"); 

console.log("Web server started"); 
var config = JSON.parse(fs.readFileSync("./private/config.json")); 

var server = http.createServer(function(req,res){ 

    console.log("received request: " + req.url); 
    fs.readFile("./public" + req.url,function(error,data){ 

     if (error){ 

      // Not sure if this is a correct way to set the default page? 
      if (req.url === "/"){ 
       res.writeHead(200,{"content-type":"text/plain"}); 
       res.end("here goes index.html ?"); 
      } 

      res.writeHead(404,{"content-type":"text/plain"}); 
      res.end(`Sorry the page was not found.\n URL Request: ${req.url}`); 
     } else { 
      res.writeHead(200,{"content-type":"text/plain"}); 
      res.end(data); 
     } 

    }); 
}); 

지금 나는 내 웹 서버가 새 포트에 다시 시작하고 듣고 싶은를 할 때 포트 번호 구성 파일의 변경 사항. 이 잘 작동

fs.watch("./private/config.json",function(){ 
    config = JSON.parse(fs.readFileSync("./private/config.json")) 
    server.close(); 
    server.listen(config.port,config.host,function(){ 
     console.log("Now listening: "+config.host+ ":" +config.port); 
    }); 
}); 

내가 설정 파일의 포트를 변경할 때, 나는 새 포트에 내 웹 서버에 액세스 할 수 있습니다 : 그래서 코드 아래에 추가합니다. 그러나 이전 포트에서도 액세스 할 수 있습니다. 나는 새로운 포트를 듣기 전에 이전 포트에서 웹 서버를 닫고 있다고 생각했습니다. 내가 뭘 놓치고 있니?

나는 당신의 도움 :)

+0

내 2 센트, 설명 https://nodejs.org/api/net.html#net_server_close_callback으로,이 새로운 연결을 승인하지 않고 기존의 연결을 유지합니다. –

+0

'keep-alive'는 서버가 연결을 닫지 않게하는 원인이된다고 생각합니다. –

+0

대신 nodemon을 사용하지 마십시오 – UchihaItachi

답변

0

무 케시 샤르마가 언급 한 바와 같이, Server.close()가 새로운 연결을 승인하지 않고 기존의 연결을 유지를 주셔서 감사합니다. 즉, 서버는 모든 활성 소켓 (활성 상태로 인해 자연적으로 죽을 때까지)에 대해 열려 있지만 새 소켓은 생성되지 않습니다.

나는 그래서 링크에 GOLO 로덴 언급 제안 된 솔루션을 따라하고 일이 질문은

this question의 가능한 중복 될 수 있습니다 발견. 기본적으로 열려있는 소켓 연결을 기억하고 서버를 닫은 후에 소켓 연결을 파괴해야합니다. 여기 내 수정 된 코드입니다 :

var http = require("http"); 
var fs = require("fs"); 

console.log("Web server started"); 
var config = JSON.parse(fs.readFileSync("./private/config.json")); 

var server = http.createServer(function(req,res){ 

    console.log("received request: " + req.url); 
    fs.readFile("./public" + req.url,function(error,data){ 

     if (error){ 

      // Not sure if this the correct method ? 
      if (req.url === "/"){ 
       res.writeHead(200,{"content-type":"text/plain"}); 
       res.end("welcome to main page"); 
      } 

      res.writeHead(404,{"content-type":"text/plain"}); 
      res.end(`Sorry the page was not found.\n URL Request: ${req.url}`); 
     } else { 
      res.writeHead(200,{"content-type":"text/plain"}); 
      res.end(data); 
     } 

    }); 
}); 

server.listen(config.port,config.host,function(){ 
    console.log("listening: "+config.host+ ":" +config.port); 
}); 

var sockets = {}, nextSocketId = 0; 
server.on('connection', function (socket) { 

    // Add a newly connected socket 
    var socketId = nextSocketId++; 
    sockets[socketId] = socket; 
    console.log('socket', socketId, 'opened'); 

    // Remove the socket when it closes 
    socket.on('close', function() { 
    console.log('socket', socketId, 'closed'); 
    delete sockets[socketId]; 
    }); 

}); 

fs.watch("./private/config.json",function(){ 
    config = JSON.parse(fs.readFileSync("./private/config.json")) 
    console.log('Config has changed!'); 
    server.close(function() { console.log('Server is closing!'); }); 

    for (var socketId in sockets) { 
     console.log('socket', socketId, 'destroyed'); 
     sockets[socketId].destroy(); 
    } 

    server.listen(config.port,config.host,function(){ 
    console.log("Now listening: "+config.host+ ":" +config.port); 
    }); 
}); 
+0

이제 다른 질문이 있습니다. 소켓 for 루프를 server.close()의 콜백 함수에 넣으려고했지만 작동하지 않았습니다. 오류는 발생하지 않지만 작동하지 않습니다. 왜 그런가요? –