Reputation: 131
I'm getting a strange results of reading the InputStream
of Socket
.
When I'm sending data from my program I'm getting a valid result ONCE.
When I'm doing it from separate program I get valid data but the server keeps on reading that same message, even if I don't send anything, just connect to a socket I get empty array.
in = socket.getInputStream();
out = socket.getOutputStream();
dIn = new DataInputStream(in);
while(this.isAlive()) {
try {
dIn.read(buffer);
StringBuilder builder = new StringBuilder();
for(int i = 0; i < buffer.length; i++) {
builder.append(buffer[i]).append(" ");
}
builder.append("\n");
System.out.println(builder.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
Output (just connecting to socket):
0 0 0 0 0 0 0 0
Upvotes: 1
Views: 504
Reputation: 140427
Quoting the javadoc for read():
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Your code is simply not at all checking that result. You assume that all bytes were read, and that simply doesn't work (sometimes).
In other words: always always always, when you call some read()
method that returns such a value, your code absolutely must check the result to ensure that (the expected) data was actually received by reading.
Most likely, this is part of your problem. But to be really sure, you will need to enhance your question with more information.
Upvotes: 2