简体   繁体   English

InputStream接收方法阻塞

[英]InputStream receive method blocking

I am stuck with the following problem. 我陷入以下问题。 I have created a connection to a remote echo server. 我已经创建了到远程回显服务器的连接。 The following method is used for receiving the bytes received from the server: 以下方法用于接收从服务器接收的字节:

public byte[] receive() {       
    byte[] resultBuff = new byte[0];
    byte[] buff = new byte[4096];
    try {
        InputStream in = socket.getInputStream();

        int k = -1;

        while((k = in.read(buff, 0, buff.length)) != -1) {
            System.out.println(k);
            byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
            System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
            System.arraycopy(buff, 0, tbuff, resultBuff.length, k);  // copy current lot
            resultBuff = tbuff; // call the temp buffer as your result buff
            String test = new String(resultBuff);
            System.out.println(test);
        }
        System.out.println(resultBuff.length + " bytes read.");         

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return resultBuff;

}

I am able to get the following response from the server: 我能够从服务器获得以下响应:

Connection to MSRG Echo server established

The problem is that the loop gets stuck at the second execution on in.read(). 问题在于循环陷入了in.read()的第二次执行。 I understand that this is due the the server not sending any EOF info and the like. 我了解这是由于服务器未发送任何EOF信息等。

I am not sure which of the following two solutions is correct and in which way to implement it: 我不确定以下两种解决方案中的哪一种是正确的,以及哪种实现方式是正确的:

  1. Each message coming from the server will be read by a new execution of the receive() method. 来自服务器的每个消息都将由新执行的receive()方法读取。 How do I prevent the in.read() method from blocking? 如何防止in.read()方法阻塞?

  2. The loop inside the receive() method should be kept alive until application exit. 在应用程序退出之前,receive()方法内部的循环应保持活动状态。 This means that my implementation is currently using in.read() wrong. 这意味着我的实现当前使用in.read()错误。 In which way should this be implemented. 应该以哪种方式实施。

The key to this question is your use of the word 'message'. 这个问题的关键是您使用“消息”一词。 There are no messages in TCP, only a byte stream. TCP中没有消息,只有字节流。 If you want messages you must implement them yourself: read a byte at a time until you have a complete message, process it, rinse and repeat. 如果需要消息,则必须自己实现:一次读取一个字节,直到获得完整的消息,进行处理,冲洗并重复。 You can amortize the cost of the single-byte reads by using a BufferedInputStream. 您可以使用BufferedInputStream摊销单字节读取的成本。

But there are no messages in an echo server. 但是回显服务器中没有消息。 Your read and accumulate strategy is therefore inappropriate. 因此,您的读取和累积策略不适当。 Just echo immediately whatever you received. 随便回声,无论收到什么。

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

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