我有一个用NodeJS编写的简单且有效的Web服务器,如下所示:
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);
}
});
});
现在,当配置文件中的端口号发生变化时,我希望我的Web服务器重新启动并侦听新端口。所以我在下面添加代码:
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);
});
});
这很好用,当我更改配置文件上的端口时,我可以在新端口上访问我的Web服务器。但是,我也可以在之前的端口上访问它。在我收听新端口之前,我以为我正在关闭上一个端口上的Web服务器。我错过了什么?
感谢您的帮助:)
答案 0 :(得分:0)
正如Mukesh Sharma所说,Server.close()停止接受新连接并保持现有连接。也就是说,服务器对所有活动套接字保持打开状态(直到它们因保持活动时间而自然死亡),但不会创建新的套接字。
我发现这个问题可能是this question
的重复所以我按照Golo Roden在链接中提到的建议解决方案进行操作。基本上,您需要记住打开套接字连接并在关闭服务器后销毁它们。这是我修改过的代码:
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);
});
});