简体   繁体   中英

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(). I understand that this is due the the server not sending any EOF info and the like.

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. How do I prevent the in.read() method from blocking?

  2. The loop inside the receive() method should be kept alive until application exit. This means that my implementation is currently using in.read() wrong. 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. 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.

But there are no messages in an echo server. Your read and accumulate strategy is therefore inappropriate. Just echo immediately whatever you received.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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