Using node.js to listen on 2 different ports

前端 未结 1 580
不思量自难忘°
不思量自难忘° 2021-01-30 17:37

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 simultan

相关标签:
1条回答
  • 2021-01-30 17:58

    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
    
    0 讨论(0)
提交回复
热议问题