markabrahams / node-net-snmp

JavaScript implementation of the Simple Network Management Protocol (SNMP)
206 stars 97 forks source link

Calling session.close() #226

Closed JasMetzger closed 1 year ago

JasMetzger commented 1 year ago

I am finding that the UDP socket is open after a call. But where in the examples is the session.close() to be called, say after a walk() command? can this be performed in the done CB?

gavinaiken commented 1 year ago

Yes, the done callback is a good place to call session.close(). You want to make sure you always do it, regardless of errors.

JasMetzger commented 1 year ago

Thank you--I thought so.

In this function I call meander, the session.close() happens in the done callback. But the session object is not passed into the callback. Since this is a promise, I think it's ok to use session still.

function meander(bindaddress, hostaddress, hostport, username, authtypestr, authpass, privtypestr, privpass, contextname, contextengine, oneoid) { return new Promise((resolve, reject) => {

    function meanderDoneCB (error) 
    {
        if (error)
            reject(error.toString ());

        // done witout error
        resolve();

        session.close();
    }

    function meanderFeedCB (varbinds) 
    {
        for (var i = 0; i < varbinds.length; i++) 
        {
            if (snmp.isVarbindError (varbinds[i]))
            {
                reject(snmp.varbindError(varbinds[i]));
            }
            else
            {
                switch (varbinds[i].type) 
                {
                    case snmp.ObjectType.Boolean:
                         // value is a boolean
                        console.log(`${String(varbinds[i].oid)}: ${varbinds[i].value.toString()} (Boolean)`);
                        break;
                  ...
                }
            } 
        }          
    }

    var session = setupV3Session(bindaddress, hostaddress, hostport, username, authtypestr, authpass, privtypestr, privpass, contextname, contextengine);

    var maxRepetitions = 20;
    session.walk(oneoid, maxRepetitions, meanderFeedCB, meanderDoneCB);
});

}

gavinaiken commented 1 year ago

Yes that is absolutely fine because session is actually declared at the top of your meander due to "hoisting". https://www.w3schools.com/js/js_hoisting.asp It isn't initialized until the var session = setupV3Session line, but since that runs before the session.close line in the meanderDoneCB executes that is also fine.

JasMetzger commented 1 year ago

Thank you!