snmp4j获取数据agent实例(三)

agent代理端例子:

 

import java.util.*;

import org.snmp4j.*;
import org.snmp4j.smi.*;
//agent代理端例子:
public class Test2 {
	
	public static class Handler implements org.snmp4j.CommandResponder {
		protected java.lang.String mAddress = null;
		protected int mPort = 0;
		protected java.lang.String mMyCommunityName = null;
		protected org.snmp4j.TransportMapping mServerSocket = null;
		protected org.snmp4j.Snmp mSNMP = null;

		public Handler() {
		}

		public void configure() {
			mAddress = "192.168.10.191";
			mPort = 161;
			mMyCommunityName = "test";
		}

		public void start() {
			try {
				mServerSocket = new org.snmp4j.transport.DefaultUdpTransportMapping(
						new org.snmp4j.smi.UdpAddress(java.net.InetAddress
								.getByName(mAddress), mPort));
				mSNMP = new org.snmp4j.Snmp(mServerSocket);
				mSNMP.addCommandResponder(this);
				mServerSocket.listen();
			} catch (java.net.UnknownHostException vException) {
				System.out.println(vException);
			} catch (java.io.IOException vException) {
				System.out.println(vException);
			}
		}

		public synchronized void processPdu(
				org.snmp4j.CommandResponderEvent aEvent) {
			java.lang.String vCommunityName = new java.lang.String(aEvent
					.getSecurityName());
			System.out.println("Community name " + vCommunityName);
			org.snmp4j.PDU vPDU = aEvent.getPDU();
			if (vPDU == null) {
				System.out.println("Null pdu");
			} else {
				System.out.println("(rcv) " + vPDU.toString());
				switch (vPDU.getType()) {
				case org.snmp4j.PDU.GET:
				case org.snmp4j.PDU.GETNEXT:
					break;
				}
				org.snmp4j.mp.StatusInformation statusInformation = new org.snmp4j.mp.StatusInformation();
				org.snmp4j.mp.StateReference ref = aEvent.getStateReference();
				try {
					System.out.println("Sending response");
					vPDU.setType(PDU.RESPONSE);
					vPDU.set(0, new VariableBinding(vPDU.get(0).getOid(),
							new OctetString("Test")));

					aEvent.getMessageDispatcher().returnResponsePdu(
							aEvent.getMessageProcessingModel(),

							aEvent.getSecurityModel(),
							aEvent.getSecurityName(),

							aEvent.getSecurityLevel(), vPDU,
							aEvent.getMaxSizeResponsePDU(), ref,

							statusInformation);
				} catch (org.snmp4j.MessageException vException) {
					System.out.println(vException);
				}
			}
		}
	}

	public static void main(String argv[]) {
		Handler h = new Handler();
		h.configure();
		h.start();
		/** Do nothing loop * */
		while (true) {
			synchronized (Test2.class) {
				try {
					Test2.class.wait();
				} catch (Exception e) {
				}
			}
		}
	}
}

 

你可能感兴趣的:(java,.net)