【问题标题】:input.read() func. lock in the while loopinput.read() 函数。锁定在while循环中
【发布时间】:2011-08-18 14:52:15
【问题描述】:

连接到服务器后,我在服务器上运行一些命令,然后尝试将服务器知识用于控制台;

while(i!=-1){
                String c="";
                String line = "";

                    try {
                        while ((i = input.read()) != 10 && i!=-1) {
                            bx[0] = (byte) i;
                            c = new String(bx);
                            line = line + c ;
                            System.out.print(c);
                        }
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }   
                    File outfile = new File("calltrak.txt");
                    boolean append = true;
                    try
                    {
                        if (!outfile.exists())
                        {
                            append = false;
                        }
                        FileWriter fout1 = new FileWriter("calltrak.txt",append);
                        PrintWriter fileout = new PrintWriter(fout1,true);
                        fileout.println(line);
                        fileout.flush();
                        fileout.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    disp.append(line);
            }

但是问题是当程序从服务器窗口读取所有行时,在服务器中它等待新的输入,而我的程序仍然试图读取该行,所以它被锁定了......我该如何解决这个问题......(注意:使用计时器不是解决办法,因为程序读取的行数可能是 100 行或 100000 行,有时服务器会运行缓慢)(代码中“disp”是 Jpanel 名称)

【问题讨论】:

  • BufferedReader 用于从流中读取字符和行。
  • BufferedReader 导致同样的问题...

标签: java sockets inputstream


【解决方案1】:

我使用并行线程解决了这个问题。在启动 Inputstream 读取方法时,我还启动了另一个线程并在其中放置了一个计时器。如果读取方法等待超过 5 秒,则其他线程将 -1 发​​送到第一个循环,因此循环终止。

【讨论】:

    【解决方案2】:

    您的代码在性能方面存在几个问题,但要回答您的问题,您应该让服务器在最后发送一个 EndOfText 0x3 或 EndOfTransmission 0x4 看到AsciiTable 这样您就可以终止了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2021-12-03
      • 2021-01-14
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2017-06-07
      相关资源
      最近更新 更多