简体   繁体   English

Java BufferedReader,如果不阻塞怎么调用?

[英]Java BufferedReader, how to only call if will not block?

I have 2 sockets and I am using BufferedReader around it's InputStreams. 我有2个套接字,并且在它的InputStreams周围使用BufferedReader。 What I am trying to do is take all input from the first socket and send it to the other socket (and visa versa). 我想做的是从第一个插座获取所有输入,然后将其发送到另一个插座(反之亦然)。

The problem is that if the first one does not send a message, it will still block on the first readLine() even though the 2nd socket has already sent some data and is ready. 问题是,如果第一个套接字不发送消息,则即使第二个套接字已经发送了一些数据并准备就绪,它仍将在第一个readLine()上阻塞。 I would like to continue with this simple approach of using no additional threads. 我想继续使用不使用其他线程的简单方法。

Here's some code that I wrote up, as you can see I have 2 BufferedReaders (in0 and in1) , the program gets stuck at in0.readLine() (blocking). 这是我写的一些代码,如您所见,我有2个BufferedReaders(in0和in1),程序停留在in0.readLine()处(阻塞)。

private void network()
{
    PrintWriter out0 = null, out1 = null;
    BufferedReader in0 = null,in1 = null;
    try{
            //clients[] is an array of Socket[2]
        in0 = new BufferedReader(new InputStreamReader(clients[0].getInputStream()));
        out0 = new PrintWriter(clients[0].getOutputStream(), true);
        in1 = new BufferedReader(new InputStreamReader(clients[1].getInputStream()));
        out1 = new PrintWriter(clients[1].getOutputStream(), true);
      } catch (IOException e) {
        System.out.println("Accept failed: 4445");
        System.exit(-1);
      }

    int count = 1;
    while(true)
    {
        System.out.println("network check loop # " + count);
        ++count;
        String nextMessage = null;
        try {
            if( (nextMessage = in0.readLine()) != null)
            {
                this.relayMessage(nextMessage,out1);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Middle of network check loop");
        nextMessage = null;

        try {
            if((nextMessage = in1.readLine()) != null)
            {
                this.relayMessage(nextMessage,out0);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

How can I just skip that statement if in0 is not ready to give me some data? 如果in0还没有准备好给我一些数据,我该如何跳过该语句? I have seen BufferedReader's ready() method and have attempted to use in0.ready() && readLine() but this causes an infinite loop as neither of the bufferedreaders appear to ever be 'ready'. 我已经看到了BufferedReader的ready()方法,并尝试使用in0.ready() && readLine()但这会导致无限循环,因为两个bufferedreader似乎都不是“就绪”的。 As well, I am certain that the messages being sent over the socket end in newline characters so readLine() should process correctly! 同样,我确定通过套接字发送的消息以换行符结尾,因此readLine()应该正确处理!

Any ideas? 有任何想法吗?

在这里, break and Continue关键字是您的朋友。

尝试使用setSoTimeout在您的read()上放置一个超时,然后如果计时器已过期, 则只需要捕获SocketTimeoutException。

The simplest approach is to use two threads. 最简单的方法是使用两个线程。 This way you don't have to write your own scheduling code to determine which thread should be running. 这样,您不必编写自己的调度代码即可确定应该运行哪个线程。 BTW: The code to copy from one socket to another is the same in each thread, reducing duplication. 顺便说一句:从一个套接字复制到另一个套接字的代码在每个线程中都是相同的,从而减少了重复。

To manage your threads I would use an ExecutorService which will make shutting downt eh threads easier. 为了管理您的线程,我将使用ExecutorService,它将使关闭线程变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM