使用 node.js 侦听 2 个不同的端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15098823/
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
Using node.js to listen on 2 different ports
提问by Josh Jones
I'm currently using Sockets.io to communicate with clients, sending JSON and whatnot, from a port.
我目前正在使用 Sockets.io 与客户端通信,从端口发送 JSON 等等。
That's all working good, but what i'd like to do is listen simultaneously on another port to create a type of administration page for testing purposes.
这一切都很好,但我想做的是同时侦听另一个端口以创建一种用于测试目的的管理页面。
For example, the page would have a button to send a certain type of JSON for all the clients connected on the other port.
例如,页面将有一个按钮,用于为在另一个端口上连接的所有客户端发送某种类型的 JSON。
If this isn't ideal, any help on other simple solutions would be great.
如果这不理想,对其他简单解决方案的任何帮助都会很棒。
回答by Herman Junge
Just create another instance of http and put it to listen to the port you are interested. Let me show you an example:
只需创建另一个 http 实例并将其用于侦听您感兴趣的端口。让我给你看一个例子:
var http = require('http');
http.createServer(onRequest_a).listen(9011);
http.createServer(onRequest_b).listen(9012);
function onRequest_a (req, res) {
res.write('Response from 9011\n');
res.end();
}
function onRequest_b (req, res) {
res.write('Response from 9012\n');
res.end();
}
Then, you can test it (with your browser, or curl):
然后,您可以对其进行测试(使用浏览器或curl):
$ curl http://localhost:9011
Response from 9011
$ curl http://localhost:9012
Response from 9012

