在java中同时使用Button和Timer

时间:2015-04-27 06:59:26

标签: java sockets

我有两个按钮和Timer。当我运行代码时,它连接到Socket。每1000毫秒计时器应该将命令(消息)发送到套接字,同时当我单击一个按钮时,它应该发送代码中的其他消息。但问题是当我点击一个按钮时,发送的消息被延迟或消息没有通过dat正确发送,接收端没有正确接收。 如何处理这个问题?

这是我的代码

public static void main(String[] args)
{
    // TODO Auto-generated method stub
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

            configure config=new configure();
            config.run();
            config.setVisible(true);                
        }
    });
}

protected void run() 
{
    // TODO Auto-generated method stub

     try {
         connection.setText("Connected to < NONE >");
        socket=new Socket("192.168.1.3",3000);
//      System.out.println("Connection Established") ;
        connection.setText("CONNECTION ESTABLISHED WITH : " + "< " + 
                            socket.getInetAddress() + " >" + "\n");

    } catch (UnknownHostException e)
     {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
     catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    //  System.out.println("connection failed");
        connection.setText("CONNECTION FAILED");
    }
}

public configure()
{
    setResizable(false);
    setBounds(300,80,800,600);
    contentPane=new JPanel();
    contentPane.setBorder(new EmptyBorder(5,5,5,5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    configlabel=new JLabel("CONFIGURE YOUR MODEL");
    configlabel.setBounds(210,20,500,40);
    configlabel.setFont(new Font("arial",Font.BOLD,28));
    contentPane.add(configlabel);

    connection=new JLabel();
    connection.setBounds(12,80,500,40);
    connection.setFont(new Font("arial",Font.BOLD,16));
    contentPane.add(connection);

    channel1=new JLabel("Channel 1");
    channel1.setBounds(80, 140, 80, 30);
    channel1.setFont(new Font("arial",Font.BOLD,15));
    contentPane.add(channel1);

    channel1Field=new JTextField();
    channel1Field.setBounds(55, 200, 120, 30);
    channel1Field.setEnabled(true);     
    contentPane.add(channel1Field);

    channel1send=new JButton("Send 1");
    channel1send.setBounds(65, 270, 100, 30);
    channel1send.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) 
        {
            if(!(channel1Field.getText().equals("")))
            {
            // TODO Auto-generated method stub
               if(channel1send.isEnabled())
                 {

                    new Thread(new Channel1()).start();                                       
                 }
            }
            else
            {
                 JOptionPane optionPane = new JOptionPane("Field cannot be 
                 empty", JOptionPane.ERROR_MESSAGE);
                 JDialog dialog = optionPane.createDialog("FAILURE");
                 dialog.setAlwaysOnTop(true);
                 dialog.setVisible(true);
            }
        }
    });
    contentPane.add(channel1send);

    channel2=new JLabel("Channel 2");
    channel2.setBounds(255, 140, 80, 30);
    channel2.setFont(new Font("arial",Font.BOLD,15));
    contentPane.add(channel2);

    channel2Field=new JTextField();
    channel2Field.setBounds(230, 200, 120, 30);
    channel2Field.setEnabled(true);
    contentPane.add(channel2Field);

    channel2send=new JButton("Send 2");
    channel2send.setBounds(250, 270, 80, 30);
    channel2send.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            if(!(channel2Field.getText().equals("")))
            {
             if(channel2send.isEnabled())
             {
                 new Thread(new Channel2()).start();    
             }
             }
               else
                {
                     JOptionPane optionPane = new JOptionPane("Field cannot     
                      be empty", JOptionPane.ERROR_MESSAGE);
                     JDialog dialog = optionPane.createDialog("FAILURE");
                     dialog.setAlwaysOnTop(true);
                     dialog.setVisible(true);
                }
        }
    });
    contentPane.add(channel2send);

 Timer timer = new Timer();
 timer.schedule(new SayHello(), 0, 1000);
}

    class SayHello extends TimerTask {
    public void run() {
        try
        {   
        byte[] com=new byte[]{0x01,(byte)0xFE};
        socket=new Socket("192.168.1.3",3000);
        DataOutputStream dw=new DataOutputStream(socket.getOutputStream()); 
        dw.writeInt(com.length);
        dw.write(com);
        StringBuilder sb=new StringBuilder();       
        for(byte b:com)
          {
            sb.append(String.format("%02X ", b));
          }
          sentmessage.append("Timer Sent -  " + sb.toString() + "\n");
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
  }


class Channel1 implements Runnable
{
    @Override
    public void run()
    {
        // TODO Auto-generated method stub
         try {

                String message1=channel1Field.getText();
                int msg1=Integer.parseInt(message1);
   command=new byte[]{(byte)0xFE,0x01,0x01,(byte)msg1,0x00,0x00,(byte)0xFD};
        DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
        //      dw.writeInt(command.length);
                dw.write(command);
                StringBuilder sb=new StringBuilder();
        //      System.out.println(Arrays.toString(command));
                for(byte b:command)
                  {
                    sb.append(String.format("%02X ", b));

                  }
                  sentmessage.append("Client Sent to Channel 1 -  " +       
                                       sb.toString() + "\n");

            } 
            catch (IOException e1) 
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                sentmessage.append("channel 1 failed to send");
            }
           finally
           {
               if(socket!=null)
               {
                   try 
                   {
                    socket.close();
                    socket=new Socket("192.168.1.3",3000);
                   } 
                   catch (IOException e1)
                   {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                   }
               }
           }
    }
}

class Channel2 implements Runnable
{
    @Override
    public void run()
    {
        // TODO Auto-generated method stub
        try {
            String message2=channel2Field.getText();
            int msg2=Integer.parseInt(message2);
    command=new byte[]{(byte)0xFE,0x01,0x02,(byte)msg2,0x00,0x00(byte)0xFD};
        DataOutputStream dw=new DataOutputStream(socket.getOutputStream());
    //      dw.writeInt(command.length);
            dw.write(command);
            StringBuilder sb=new StringBuilder();

            for(byte b:command)
              {
                sb.append(String.format("%02X ", b));
              }
              sentmessage.append("Client Sent to Channel 2 -  " + 
                                    sb.toString() + "\n");

        } 
        catch (IOException e1) 
        {
            e1.printStackTrace();
            sentmessage.append("channel 2 on failed");
        }
       finally
       {
           if(socket!=null)
           {
               try {
                socket.close();
                socket=new Socket("192.168.1.3",3000);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
           }
       }
    }
}

0 个答案:

没有答案