简体   繁体   English

使用node.js监听2个不同的端口

[英]Using node.js to listen on 2 different ports

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. 如果这不是理想的,那么对其他简单解决方案的任何帮助都会很棒。

Just create another instance of http and put it to listen to the port you are interested. 只需创建另一个http实例并将其用于监听您感兴趣的端口。 Let me show you an example: 让我举个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM