开发者

Java - InputStream - Test for input

开发者 https://www.devze.com 2023-03-08 19:48 出处:网络
I am sending data to a server in two steps: 1) Length of what I will send using byte[4] 2) Data. The server listens to the exact length of the data (shipped first) and then replies.

I am sending data to a server in two steps: 1) Length of what I will send using byte[4] 2) Data.

The server listens to the exact length of the data (shipped first) and then replies.

So I listen to the InputStream and try to get the data.

My Problem: Whatever I am doing I am getting only the stream I send, but the server definatly sends a new string.

It seems I c开发者_运维知识库annot wait for a -1 (end of string), as the program would time out and I am sure the server does not send anything alike.

Therefore I am using inputStream.available() to find out how many bytes are left in the buffer.

Once I am sending inputStream.read() after reading all the data it will time out with "Network idle timeout".

But I need to listen to the inputStream to make sure I am not missing information.

Why am I only receiving the information I send and not what is send by the server? How can I listen to the connection for new items coming in?

Here is my code:

    private void sendData (byte[] sendBytes){
        try {
            os.write(sendBytes);
            os.flush();
        } catch (IOException ex) {
        }
    }

Please help THD


This is how you normally read all data from a reader (until the other end closes):

//BufferedReader is 
StringBuilder data = new StringBuilder();
char[] buffer = new char[1024 * 32];
int len = 0;
while ((len = is.read(buffer)) != -1) {
    data.append(buffer, 0, len);
}

//data will on this line contain all code received from the server

0

精彩评论

暂无评论...
验证码 换一张
取 消