我有一个简单且有效的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服务器。我想念什么?
我感谢您的帮助:)
如Mukesh Sharma所述,Server.Close()停止接受新的连接并保持现有连接。也就是说,服务器对所有活着的插座都保持开放(直到它们自然会因保持时间而死),但不会创建新的插座。
我发现这个问题可能是这个问题的重复
因此,我遵循了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);
});
});