【问题标题】:tcp sniffer doesn't produce outputtcp 嗅探器不产生输出
【发布时间】:2012-02-04 17:18:08
【问题描述】:

我正在做一个 tcp 嗅探器项目。起初,我使用 JCreator 创建了系统,它没有任何界面就可以正常工作。接下来,我尝试使用 NetBean 7.1 为其创建用户界面。当然,我必须将代码分成几部分才能安装到按钮功能中。似乎当我运行程序时,它不会产生任何输出,而是继续运行直到手动停止。当我尝试插入“打开设备”代码时会发生这种情况。我怀疑导致问题的另一部分是“Thread.sleep(25);”部分..在插入该部分之前,我尝试运行并产生输出,即框架、按钮等。

以下是程序。非常需要我能从这里得到的任何帮助。

谢谢

import java.util.ArrayList;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.PacketReceiver;
import jpcap.packet.Packet;
import jpcap.packet.TCPPacket;

public class NewJFrame extends javax.swing.JFrame {

    NetworkInterface[] devices = JpcapCaptor.getDeviceList();
    static int deviceNum=0;
    JpcapCaptor captor;
    PacketStorage ps;

    public NewJFrame() {
        initComponents();
      for(int i=0;i<devices.length;i++)
      {
          jComboBox1.addItem(""+devices[i].name);
      }   
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton2.setText("Stop");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(22, 22, 22))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(27, 27, 27))
        );

        jMenu1.setText("File");

        jMenuItem1.setText("Run");
        jMenu1.add(jMenuItem1);

        jMenuItem3.setText("Stop");
        jMenu1.add(jMenuItem3);

        jMenuItem2.setText("Exit");
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        jMenu3.setText("About");
        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        deviceNum = jComboBox1.getSelectedIndex();
      try{
        **captor=JpcapCaptor.openDevice(devices[deviceNum], 65535, true , 20);**
      }
      catch(Exception ex1){System.out.println("Cannot open device");}
      ps = new PacketStorage();
      new Thread(new Parser(ps)).start();

      captor.loopPacket(-1, ps);
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    private static class PacketStorage implements PacketReceiver
   {
      private ArrayList<Packet> packets = new ArrayList<>();

      public void receivePacket(Packet p)
      {
         packets.add(p);
      }
      public Packet getPacket()
      {
         return packets.size()>0?packets.remove(0):null;
      }
   }

    private static class Parser implements Runnable
   {
      PacketStorage ps1;
      public Parser(PacketStorage ps2)
      {
         this.ps1=ps2;
      }


      public void run()
      {
         Packet p;
         TCPPacket tcp;

         while(true)
         {
            p=ps1.getPacket();
            if(p!=null && p instanceof TCPPacket )
            {
               tcp =(TCPPacket)p;
               jTextArea1.append("Src: " + tcp.src_ip + ":" + tcp.src_port + " Dst: " + tcp.dst_ip + ":" + tcp.dst_port+"\n");
               jTextArea1.append("Sequence Number Value: " + tcp.sequence + " Ack Number: " + tcp.ack_num+"\n");

            }

          try{
               **Thread.sleep(25);**
          }
          catch(InterruptedException e){}

         }
      }
   }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTextArea jTextArea1;
    // End of variables declaration                   
}

【问题讨论】:

    标签: java swing tcp netbeans-7 concurrency


    【解决方案1】:

    部分你是对的,Concurency in Swing 有问题

    • Swing 是单线程的,所有到 Swing GUI 的输出都必须在 EDT 上完成

    • 您正在运行长时间且繁重的任务,其中向 GUI 的输出超出 EDT,包括声明的 thread_safe 方法,

    • 您可以通过将 JTextArea#append() 包装到调用 EDT 的 invokeLater() 中来简单地解决这个问题

    • 正确的方法是从 SwingWorker 调用此代码,从方法 publish() 你可以更新 JTextArea 并且输出应该在 EDT 上

    【讨论】:

      【解决方案2】:

      关于:

       while(true)
       {
          p=ps1.getPacket();
          if(p!=null && p instanceof TCPPacket )
          {
             tcp =(TCPPacket)p;
             jTextArea1.append("Src: " + tcp.src_ip + ":" + tcp.src_port + " Dst: " + tcp.dst_ip + ":" + tcp.dst_port+"\n");
             jTextArea1.append("Sequence Number Value: " + tcp.sequence + " Ack Number: " + tcp.ack_num+"\n");
      
          }
      
        try{
             Thread.sleep(25);
        }
        catch(InterruptedException e){}
      
       }
      }
      

      问题:您在哪里突破 while (true) 循环?
      答:没有。
      解决方案:解决这个问题。

      【讨论】:

      • @din:如果您仍然卡住,请在此处回复评论,我可以进一步帮助您。
      猜你喜欢
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 2011-09-02
      • 1970-01-01
      • 2011-03-07
      相关资源
      最近更新 更多