Reputation:
I have a class that serves as a client thread.
in the class i have a run
method that deals with the reading and writing operations from and to the socket.
my run method looks like this:
public void run(){
System.out.println("New connection at " + new Date() + "\n");
try {
DataInputStream in = new DataInputStream (threadSocket.getInputStream());
out = new DataOutputStream (threadSocket.getOutputStream());
while (running){
// read input from client
byte[] input = new byte [200];
int count = in.read(input);
if (count == -1) {
running = false;
break;
}
String msg = new String(input, 0, count);
// parse in going message
messageParsing(msg);
// respond to client
response();
}
}
catch (IOException ex) {ex.printStackTrace();}
finally {
try {
threadSocket.close();
System.out.println("Connection closed.\n");
} catch (IOException ex) {ex.printStackTrace();}
}
}
I have created a fixed size byte array and i am reading the data from the socket into it. The available lengths of the data coming in are 147 and 61, if the length of the input data is 0 it does not mean any thing. I would like to close the socket when the count is -1, but i am not successful. It seems like when the there is no data, count is 0 it just keeps trying to read data from the socket and it gets stuck.
How can i fix this problem? What am i doing wrong? Any help would be appreciated.
Upvotes: 0
Views: 33
Reputation: 310893
Cannot reproduce. Your code can never get zero from a read. If you aren't getting -1 it is because the peer never closes the connection.
Upvotes: 0
Reputation: 1189
The Stream can only return -1, i.e. signal the end, when the other communication side has actually closed its output so that it is guaranteed that no more data is transferred.
Upvotes: 1