无法连接到nodejs服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18852152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't connect to nodejs server
提问by user2787904
I run Apache on my server. Going to my address x.x.x.x:port loads the index.html page in /var/www. When I stop the server, I can no longer connect (all good).
我在我的服务器上运行 Apache。转到我的地址 xxxx:port 加载 /var/www 中的 index.html 页面。当我停止服务器时,我无法再连接(一切正常)。
Now I start the node server with node server.js(the server.js file below is also located in /var/www).
现在我启动节点服务器node server.js(下面的 server.js 文件也位于 /var/www 中)。
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(port, 'x.x.x.x');
console.log('Server running at http://x.x.x.x:port/');
This gives the error listen EADDRNOTAVAIL, but I am not running any other node server (there is no other process running at this port).
这给出了错误listen EADDRNOTAVAIL,但我没有运行任何其他节点服务器(此端口上没有其他进程在运行)。
I have also tried omitting the IP address and just listening thus: listen(port);
我也试过省略 IP 地址,只听这样: listen(port);
This returns no errors, but I cannot connect to the server (Browser says: Firefox can't establish a connection to the server at x.x.x.x:p.)
这将返回没有错误,但我无法连接到服务器(浏览器说:Firefox can't establish a connection to the server at x.x.x.x:p.)
回答by user2787904
I have found out the problem. You don't need to specify a host name:
我发现了问题所在。您不需要指定主机名:
listen(port, 'x.x.x.x')
listen(port, 'x.x.x.x')
should just be
应该只是
listen(port)
listen(port)
otherwise the server will not accept any connection except ones directed at the specified ip.
否则服务器将不接受任何连接,除了指向指定 ip 的连接。
回答by seumasmac
The port is in use or not available. Try a different port like:
端口正在使用或不可用。尝试不同的端口,例如:
listen(88, 'x.x.x.x');
and see if that connects. Also, make sure that x.x.x.x is actually the ip address of your server. You can listen on all IPs by doing:
看看是否有联系。另外,请确保 xxxx 实际上是您服务器的 IP 地址。您可以通过执行以下操作来侦听所有 IP:
listen(88, '0.0.0.0');
or by leaving the host/ip section out entirely. If it does connect on another port, you just need to find what is using the port you want. If it's port 80, use:
或者完全保留主机/IP 部分。如果它确实连接到另一个端口,您只需要找到正在使用您想要的端口的内容。如果是 80 端口,请使用:
sudo netstat -tulpn | grep :80
to get the program using that port.
使用该端口获取程序。
回答by Alec.
Sounds like the port is locked up and in use..
听起来端口已被锁定并正在使用中..
The following command will give you a list of node processes running.
以下命令将为您提供正在运行的节点进程列表。
ps | grep node
To free up that port, stop the process using the following.
要释放该端口,请使用以下命令停止该进程。
kill <processId>

