简体   繁体   中英

How to detect end of Input Stream from Socket using BufferedInputStream?

I'm trying to read and input from a Socket in Java and then proccess it by calling a function. I must read by byte and not by text because reading as text give some erros because of the requests coming from client. So I decided to use the class BufferedInputStream . The problem is that the end of a request is not being detected. I guess that this is because the stream is not ending just being hanged or something...

According to the documentation , the read() function returns a byte read from the stream or -1 if the stream has ended. So, my code reads byte by byte, joins it in a string, and then, when the stream has ended, sends the string to be proccessed (or at least, was supposed to do this). Here is the code:

BufferedInputStream reader = new BufferedInputStream(socket.getInputStream());
int dt;   
String cmd = "";

while( (dt = reader.read()) >= 0){
  cmd += (char)dt == '\n' || (char)dt == '\r' ? ' ' : (char)dt; // add each byte read to the string 
  System.out.println(cmd);
}

processaInput(cmd);

The problem is that the function processaInput is never being called like if the program was stuck in the loop. But even more stranger is that is not stuck on the loop because the system.out.println stops being called after the stream has ended. By the way, this while is being ran in a Thread (run() function), don't know if this can mess up so I added this last info here. Anyway, what am I missing here? Thanks.

Edit: There is no Client side code because I'm using the app POSTMAN from google to test it, so it is just sending HTTP request to my program.

You are conflating 'end of request' with 'end of stream'.

'End of stream' on a socket means the peer has closed the connection. No end of stream, no peer close. If you plan to write a response back down this socket, it is therefore incorrect to try to read it to end of stream first.

You are trying to read a single request, in which case you need something in your application protocol to tell you when you have it all: lines; a length word prefix; a self-describing protocol like XML; STX/ETX; type-length-value; ...

In this case if the protocol is HTTP you need to implement the Content-length header: recognise it, read to the end of the headers, then read exactly that many bytes from the stream, eg with DataInputStream.readFully() .

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