On Wed, May 15, 2013 at 1:05 PM, Васим Абу-Нассар <[email protected]> wrote:
> Hello.
> I have following code.
> Why its always outputs LAST port (27114)? What's wrong?

Please post code examples inline, people may not be able to access the
website you're linking to.  I'll include your snippet here for
posterity:

    var dgram = require("dgram");
    var start = 27015;
    for(var i = start; i < (start + 100); i++)
    {
            var server = dgram.createSocket("udp4");
            server.on("message", function(msg, sender) {
                    console.log(server.address().port)
            });
            server.bind(i);
    }

You're reassigning the server variable on each iteration.  JS closures
close over the variable itself, not its value at the time of closure.
If you wrap the body of the loop in a function, each function gets its
own copy of the server variable.

Alternatively, you can use this.address() rather than server.address()
inside the event listener.

-- 
-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to