socket发送后,接收线程用while(1){get = br.readline(); if(get!=null){recvdata = get;}}在主程序中写入流(发送),怎样在接受线程接到数据时立即再主程序中处理?

解决方案 »

  1.   


    就是一个Frame或者一个class里面启动线程,然后要监控线程里的变量变化
    public class Frame1 extends JFrame {
            // 建立连接
            try
            {
                connection = new Socket(InetAddress.getLocalHost(),8021);
                JOptionPane.showMessageDialog(this,"连接成功");
            }catch(Exception es)
            {
                JOptionPane.showMessageDialog(this,"错误2"+es.toString());
            }
            // 发送
            try
            {
                // io流
                is = connection.getInputStream();
                os = connection.getOutputStream();
                br = new BufferedReader(new InputStreamReader(is));
                pw = new PrintWriter(os);
                // 线程
                t1 = new Thread(new receiver());
                t1.start();
            } catch (Exception es) {
                JOptionPane.showMessageDialog(this, "错误" + es.toString());
            }
      class receiver implements Runnable
        {
            public receiver()
            {
            }
            public void run()
            {
                
                while(true)
                {
                    try
                    {
                        changableValue = br.readLine();
                        if(changableValue != null)
                        {
                          recvdata = changableValue ;
                        }
                        else
                        {
                        }
                    }catch(Exception ex)
                    {
                        //JOptionPane.showMessageDialog(null, "错误1" + ex.toString());
                    }
                }
            }    }
    }
      

  2.   

    Swing的话,将其它线程里得到的数据,及处理过程,封装成一个 Runnable 任务,提交给 Swing线程执行
    1。SwingUtilities.invokeAndWait(Runnable r)阻塞执行
    2。SwingUtilities.invokeLater(Runnable r)异步执行changableValue   =   br.readLine();
    if(changableValue==null)
       break;
    else{
       final String v = changableValue;
       SwingUtilities.invokeLater(new Runnable(){
          public void run(){
              //将v显示到Swing界面组件上
          }
       });
    }                                        if(changableValue   !=   null) 
                                            { 
                                                recvdata   =   changableValue   ; 
                                            } 
                                            else 
                                            { 
                                            } 
      

  3.   

    上面回复里后面一段代码忘了删,无视之CSDN 怎么不能编辑自己的回帖,真要命