简体   繁体   中英

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.

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.

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. 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 http://localhost:9011
Response from 9011

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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