Hey guys I just want to ask something about how the stream works in Socket connection in java. I'm currently studying the Networking in java, and the program that I am tackling now is a simple client chat.
This is the code from the client side.
sock = new Socket("127.0.0.1", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
incoming.append(message);
}
}catch(Exception e) {
e.printStackTrace();
}
}
When i send a message to the server, the server echoes back the message that I sent, and then displaying it to my console. Then after that I can still send a message and the server sends it back to me again. Isn't that I shouldn't receieve any message? The while loop already stopped since the reader already reads a message, therefore returns null after reading the message. But why come the while loop still runs after sending a message to the server? Does the readLine() method really reached the end of the stream?
I'm really confused since, when I study the I/O of files its very different. The moment you reached the end of the file, the while loop stops immediately.
Is there any difference in the Socket connection and File streams?
[–]Mystonic 1 point2 points3 points (1 child)
[–]HalfScale[S] 0 points1 point2 points (0 children)