首页 \ 问答 \ Java SNMP4J Trap应用程序正在冻结GUI(Java SNMP4J Trap application is freezing the GUI)

Java SNMP4J Trap应用程序正在冻结GUI(Java SNMP4J Trap application is freezing the GUI)

我在Java中有一个SNMP陷阱应用程序,旨在侦听SNMP代理并在JFrame窗口中的JTextArea上打印接收到的SNMP消息。

下面的第一部分是我的源代码,显示了TrapReceiver类的内容。 在这个类中,listen方法是充分利用工作的地方。 该类在JFrame类中进行实例化,我打算在上面提到的JTeaxtArea上显示消息。 我将JTextArea对象的引用,SNMP代理URL和端口发送到TrapReceiver类的构造函数中,然后调用TrapReceiver对象的run方法以在JFrame实例以外的单独线程中开始执行。 下面的第二部分展示了如何在JFrame实例中实例化TrapReeceiver类。

当我运行应用程序时,我注意到JFrame实例(即GUI)处于冻结状态,并且在JFrame实例中提到的JTeaxtArea上没有打印消息,该实例实例化了下面第一部分中所示的类TrapReeceiver。

我的问题是为什么JFrame实例(即GUI)是冻结的,尽管TRapReceiver本身是作为一个单独的线程执行的? 此外,我想知道这个冻结问题的可能解决方案是什么。 提前致谢。

PS:我已经验证了TrapReceiver工作正常并且可以在没有GUI的情况下作为独立应用程序运行时将消息打印到标准输出,但是由于某些可能的线程同步问题,这个GUI会以某种方式冻结。 我试图运行TrapReceiver而不用线程,即使在这种情况下,GUI仍然处于冻结状态。

第一部分

 package com.[Intenionally removed].snmp;

 import java.io.IOException;
 import javax.swing.JTextArea;
 import org.snmp4j.*;
 import org.snmp4j.mp.MPv1;
 import org.snmp4j.mp.MPv2c;
 import org.snmp4j.security.Priv3DES;
 import org.snmp4j.security.SecurityProtocols;
 import org.snmp4j.smi.OctetString;
 import org.snmp4j.smi.TcpAddress;
 import org.snmp4j.smi.TransportIpAddress;
 import org.snmp4j.smi.UdpAddress;
 import org.snmp4j.transport.AbstractTransportMapping;
 import org.snmp4j.transport.DefaultTcpTransportMapping;
 import org.snmp4j.transport.DefaultUdpTransportMapping;
 import org.snmp4j.util.MultiThreadedMessageDispatcher;
 import org.snmp4j.util.ThreadPool;

 public class TrapReceiver implements CommandResponder, Runnable {

   private String targetSnmpAgentURL;
   private int targetSnmpAgentPort;
   private JTextArea outConsole;

   public TrapReceiver() {
   } 

   public TrapReceiver(JTextArea outConsole) {
       this.outConsole = outConsole;
   }


   public TrapReceiver(JTextArea outConsole, String targetSnmpAgentURL, int  targetSnmpAgentPort) {
       this.targetSnmpAgentURL = targetSnmpAgentURL;
       this.targetSnmpAgentPort = targetSnmpAgentPort;
       this.outConsole = outConsole;

       try {
           listen(new UdpAddress(targetSnmpAgentURL + "/" + targetSnmpAgentPort));
       } catch (IOException e) {
           e.printStackTrace();
       }
    }

    public final synchronized void listen(TransportIpAddress address) throws IOException {


        AbstractTransportMapping transport;
        if (address instanceof TcpAddress) {
            transport = new DefaultTcpTransportMapping((TcpAddress) address);
        } else {
            transport = new DefaultUdpTransportMapping((UdpAddress) address);
        }

        ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
        MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
            threadPool, new MessageDispatcherImpl());

        // add message processing models
        mDispathcher.addMessageProcessingModel(new MPv1());
       mDispathcher.addMessageProcessingModel(new MPv2c());

        // add all security protocols
        SecurityProtocols.getInstance().addDefaultProtocols();
        SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());

        // Create Target
        CommunityTarget target = new CommunityTarget();
        target.setCommunity(new OctetString("public"));

        Snmp snmp = new Snmp(mDispathcher, transport);
        snmp.addCommandResponder(this);

        transport.listen();
        System.out.println("Listening on " + address);

        try {
           this.wait();
        } catch (InterruptedException ex) {
           Thread.currentThread().interrupt();
        }
        }

    /**
    * This method will be called whenever a pdu is received on the given port
    * specified in the listen() method
    */
    @Override
    public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
        //System.out.println("Received PDU...");
        outConsole.append("Received PDU...\n");
        PDU pdu = cmdRespEvent.getPDU();

        if (pdu != null) {            
        outConsole.append("Trap Type = " + pdu.getType() + "\n");
        outConsole.append("Alarm Type: " + pdu.getVariableBindings().get(4) + "\n");
        outConsole.append("Alarm Message:  " + pdu.getVariableBindings().get(9) +  "\n\n");

        }
     }


     @Override
     public void run() {
        try {           
            listen(new UdpAddress(targetSnmpAgentURL + "/" + targetSnmpAgentPort));
        } catch (IOException e) {
            outConsole.append("\nError occured while listening to SNMP messages: \n" + e.getMessage() + "\n\n");
        }
     }

} //end of class TrapReceiver

第二部分

在下面,我在一个线程中运行一个TrapReceiver类的实例。

   private void jButtonStartListeningSNMPActionPerformed(java.awt.event.ActionEvent evt)   {                                                          

    Thread snmpThread = 
           new Thread(new TrapReceiver(jTextAreaSNMPAlarmOutput, jTextFieldSnmpAgentUrl.getText().trim(), Integer.parseInt(jTextFieldSnmpAgentPort.getText().trim())));
    snmpThread.start()

   }

I have an SNMP trap application in Java that aims at listening to an SNMP agent and printing the received SNMP messages on a JTextArea in a JFrame window.

Part I below is my source code showing the content of class TrapReceiver. In this class, the listen method is the place that makes the most of the job. The class is intantiated within a JFrame class on which I intend to show the messages on so mentioned JTeaxtArea. I send the reference of the JTextArea object, the SNMP agent URL and the port into the constructor of the class TrapReceiver and then call the run method of TrapReceiver object to start execution in a seperate thread other than the JFrame instance. Part II below shows how I instantiate the class TrapReeceiver within the JFrame instance.

When I run the application I noticed that the JFrame instance (i.e. GUI) is freezing and no message is being printed on so mentioned JTeaxtArea within the JFrame instance which instantiates the class TrapReeceiver shown in Part I below.

My question is why the JFrame instance (i.e. GUI) is freezing although the TRapReceiver itself is executed as a separate thread? Also, I wonder what could be the possible solution to this freezing issue. Thanks in advance.

P.S.: I have verified that TrapReceiver works fine and can print messages to standard output when running as a stand alone application without GUI but it is this GUI that is freezing somehow due to some possible thread synch issue. I tried to run the TrapReceiver without putting onto a thread and even in this case the GUI was still freezing.

PART I

 package com.[Intenionally removed].snmp;

 import java.io.IOException;
 import javax.swing.JTextArea;
 import org.snmp4j.*;
 import org.snmp4j.mp.MPv1;
 import org.snmp4j.mp.MPv2c;
 import org.snmp4j.security.Priv3DES;
 import org.snmp4j.security.SecurityProtocols;
 import org.snmp4j.smi.OctetString;
 import org.snmp4j.smi.TcpAddress;
 import org.snmp4j.smi.TransportIpAddress;
 import org.snmp4j.smi.UdpAddress;
 import org.snmp4j.transport.AbstractTransportMapping;
 import org.snmp4j.transport.DefaultTcpTransportMapping;
 import org.snmp4j.transport.DefaultUdpTransportMapping;
 import org.snmp4j.util.MultiThreadedMessageDispatcher;
 import org.snmp4j.util.ThreadPool;

 public class TrapReceiver implements CommandResponder, Runnable {

   private String targetSnmpAgentURL;
   private int targetSnmpAgentPort;
   private JTextArea outConsole;

   public TrapReceiver() {
   } 

   public TrapReceiver(JTextArea outConsole) {
       this.outConsole = outConsole;
   }


   public TrapReceiver(JTextArea outConsole, String targetSnmpAgentURL, int  targetSnmpAgentPort) {
       this.targetSnmpAgentURL = targetSnmpAgentURL;
       this.targetSnmpAgentPort = targetSnmpAgentPort;
       this.outConsole = outConsole;

       try {
           listen(new UdpAddress(targetSnmpAgentURL + "/" + targetSnmpAgentPort));
       } catch (IOException e) {
           e.printStackTrace();
       }
    }

    public final synchronized void listen(TransportIpAddress address) throws IOException {


        AbstractTransportMapping transport;
        if (address instanceof TcpAddress) {
            transport = new DefaultTcpTransportMapping((TcpAddress) address);
        } else {
            transport = new DefaultUdpTransportMapping((UdpAddress) address);
        }

        ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
        MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
            threadPool, new MessageDispatcherImpl());

        // add message processing models
        mDispathcher.addMessageProcessingModel(new MPv1());
       mDispathcher.addMessageProcessingModel(new MPv2c());

        // add all security protocols
        SecurityProtocols.getInstance().addDefaultProtocols();
        SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());

        // Create Target
        CommunityTarget target = new CommunityTarget();
        target.setCommunity(new OctetString("public"));

        Snmp snmp = new Snmp(mDispathcher, transport);
        snmp.addCommandResponder(this);

        transport.listen();
        System.out.println("Listening on " + address);

        try {
           this.wait();
        } catch (InterruptedException ex) {
           Thread.currentThread().interrupt();
        }
        }

    /**
    * This method will be called whenever a pdu is received on the given port
    * specified in the listen() method
    */
    @Override
    public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
        //System.out.println("Received PDU...");
        outConsole.append("Received PDU...\n");
        PDU pdu = cmdRespEvent.getPDU();

        if (pdu != null) {            
        outConsole.append("Trap Type = " + pdu.getType() + "\n");
        outConsole.append("Alarm Type: " + pdu.getVariableBindings().get(4) + "\n");
        outConsole.append("Alarm Message:  " + pdu.getVariableBindings().get(9) +  "\n\n");

        }
     }


     @Override
     public void run() {
        try {           
            listen(new UdpAddress(targetSnmpAgentURL + "/" + targetSnmpAgentPort));
        } catch (IOException e) {
            outConsole.append("\nError occured while listening to SNMP messages: \n" + e.getMessage() + "\n\n");
        }
     }

} //end of class TrapReceiver

PART II

In the following, I run an instance of class TrapReceiver within a thread.

   private void jButtonStartListeningSNMPActionPerformed(java.awt.event.ActionEvent evt)   {                                                          

    Thread snmpThread = 
           new Thread(new TrapReceiver(jTextAreaSNMPAlarmOutput, jTextFieldSnmpAgentUrl.getText().trim(), Integer.parseInt(jTextFieldSnmpAgentPort.getText().trim())));
    snmpThread.start()

   }

原文:https://stackoverflow.com/questions/9618096
更新时间:2022-02-17 17:02

最满意答案

看起来很破 这是逗号运算符的用法,它简单地评估为最终表达式的值,即1

因此,由于该代码相当于:

ss->elem = *i;
res = 1;

随后的res测试看起来毫无意义,因此被打破。


Looks broken. It's a use of the comma operator, which simply evaluates to the value of the final expression, i.e. 1.

Therefore, since that code is equivalent to:

ss->elem = *i;
res = 1;

The subsequent testing of res seem pointless, and thus broken.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。