Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Is it possible to listen on two net.createServer()s in a single node.js process?

Is it possible to listen on two net.createServer()s in a single node.js process?

Problem

I'm working on a test harness that interacts with another Node application and verifies that the other application works properly. I need to be able to Listen to two different protocols, on two different ports, in the same process in node.js. Specifically, I am intercepting a simple line-break text protocol (acceptorone) and HTTP requests (acceptortwo).

I currently have this:

var acceptorone = net.createServer();
acceptorone.listen(portone);
var acceptortwo = http.createServer();
acceptortwo.listen(porttwo);

Yet when I try this I get Error: listen EADDRINUSE. Both codepaths work fine independently, everything is fine if one of the listen()s is commented out.

Googling around a bit yields a solution that involves forking off several processes. However, this is running in a test framework so I need to keep everything inside the same process. Applications such as statsd have no qualms accepting TCP and UDP connections simultaneously, so I'm not sure why there would be a limitation on listening on multiple TCP sockets at the same time. Can anyone shed light on the issue? Thanks.

Problem courtesy of: wickedchicken

Solution

I think something else must be broken with your example; can you show how you initialize portone and porttwo?

$ cat servers.js 
#!/usr/bin/node
net = require('net')
http = require('http')

portone=10000
porttwo=10001

var acceptorone = net.createServer();
acceptorone.listen(portone);
var acceptortwo = http.createServer();
acceptortwo.listen(porttwo);
$ ./servers.js &
[1] 6894
$ netstat -anp | grep node
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:10000           0.0.0.0:*               LISTEN      6894/node       
tcp        0      0 0.0.0.0:10001           0.0.0.0:*               LISTEN      6894/node       
$ 
Solution courtesy of: sarnold

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Is it possible to listen on two net.createServer()s in a single node.js process?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×