使用 node.js 侦听 2 个不同的端口 [英] Using node.js to listen on 2 different ports

查看:57
本文介绍了使用 node.js 侦听 2 个不同的端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Sockets.io 与客户端通信,从端口发送 JSON 等等.

I'm currently using Sockets.io to communicate with clients, sending JSON and whatnot, from a port.

这一切都很好,但我想做的是同时侦听另一个端口以创建一种用于测试目的的管理页面.

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.

例如,页面将有一个按钮,用于为在另一个端口上连接的所有客户端发送某种类型的 JSON.

For example, the page would have a button to send a certain type of JSON for all the clients connected on the other port.

如果这不理想,对其他简单解决方案的任何帮助都会很棒.

If this isn't ideal, any help on other simple solutions would be great.

推荐答案

只需创建另一个 http 实例并将其用于监听您感兴趣的端口.让我给你举个例子:

Just create another instance of http and put it to listen to the port you are interested. 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();
}

然后,您可以对其进行测试(使用您的浏览器或 curl):

Then, you can test it (with your browser, or curl):

$ curl http://localhost:9011
Response from 9011

$ curl http://localhost:9012
Response from 9012

这篇关于使用 node.js 侦听 2 个不同的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆