daw*_*623 5 javascript port node.js server
const http = require("http");
function createServer(
name,
hostname
)
{
const server = http.createServer(
(
request,
response
) =>
{
console.log("request on", name);
response.end(name);
}
);
server.on(
"error",
(error) => console.log(`${name} error`, error)
);
server.on(
"close",
() => console.log(`${name} closed`)
);
server.listen(4321, hostname, () => console.log(`${name} listening (${server.listening}) on address`, server.address()));
}
createServer(
"Server 1",
"localhost"
);
createServer(
"Server 2",
"127.0.0.1"
);
createServer(
"Server 3",
"127.0.1.1"
);
createServer(
"Server 4",
"localhost"
);
createServer(
"Server 5",
"10.9.129.49"
);
createServer(
"Server 6",
"localhost"
);
Run Code Online (Sandbox Code Playgroud)
使用Node v6.15.1,v8.14.1和v10.15.0,上面的代码在我的计算机上打印出来:
Server 2 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 3 listening (true) on address { address: '127.0.1.1', family: 'IPv4', port: 4321 }
Server 5 listening (true) on address { address: '10.9.129.49', family: 'IPv4', port: 4321 }
Server 1 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 4 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 6 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Run Code Online (Sandbox Code Playgroud)
这怎么可能?我原本预计EADDRINUSE会触发错误.
编辑此问题的先前版本仅显示使用主机名的两台服务器localhost.代码已更新,以证明无论服务器数量或主机如何,问题似乎都会持续存在.
UPDATE
我尝试混合指向我的计算机的不同主机名(localhost,127.0.0.1我的本地IP等),即使address打印的对象显示不同的值,也address()不会发生错误.
我很好奇它是否与Node.js的server.listen方法有关,允许自己被多次调用.也许Node.js检测到我使用的所有主机名绑定到同一个设备和端口,所以它只是"重新打开",就像文档所说的那样.
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |