[SNMP4J] SNMP Async Method call
Smith, Ryan
rsmith at shsolutions.com
Mon Jul 16 20:29:05 CEST 2007
Included below is the code to reproduce the behavior I am describing.
If you run this example, the main thread dies but the async send() call
keeps the application from exiting.
How do I tell the async thread that is hanging there to end gracefully?
(ps - you can use this code to update the example on :
http://www.snmp4j.org/doc/org/snmp4j/Snmp.html
since sendPDU() doesn't exist anymore. )
-Ryan
///////////////////////////////////////////////////
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SnmpAsyncExample {
public static void main(String...args) throws IOException {
/** our mode of transport for these snmp messages (udp).
*/
TransportMapping transport = new
DefaultUdpTransportMapping();
/** The snmp class from snmp4j. */
Snmp snmp = new Snmp(transport);
Address targetAddress =
GenericAddress.parse("udp:127.0.0.1/162");
//An asynchronous SNMPv1 request is sent by the
following code:
// setting up target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version1);
// creating PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[]
{1,3,6,1,2,1,1,1})));
pdu.add(new VariableBinding(new OID(new int[]
{1,3,6,1,2,1,1,2})));
pdu.setType(PDU.GETNEXT);
// sending request
ResponseListener listener = new ResponseListener() {
public void onResponse(ResponseEvent event) {
// Always cancel async request when response has
been received
// otherwise a memory leak is created! Not canceling
a request
// immediately can be useful when sending a request
to a broadcast
// address.
((Snmp)event.getSource()).cancel(event.getRequest(),
this);
System.out.println("Received response PDU is:
"+event.getResponse());
}
};
snmp.send(pdu, target, null, listener);
System.out.println("Main thread is exiting...");
}
}
///////////////////////////////////////////////////////////
Ryan Smith
1625 South Congress Ave.
Suite 200
Delray Beach, FL 33445
Tel:(561) 454-7600
www.shsolutions.com <http://www.shsolutions.com/>
More information about the SNMP4J
mailing list