Im trying to create a simple chat program, with a "server" and a client, now my problem is that the program blocks while reading messages from the server to the client and vice-versa. This example features the problem with messages from Client to Server.
Example of what I have on the server side:
private Reader input;
private Writer output;
try {
server = new ServerSocket(this.port);
while (true) {
Socket connection = server.accept();
serverDisplay("We have a connection");
input = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
output = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream()));
int c;
StringBuffer sb = new StringBuffer();
// This is where it blocks, the input stream should return -1 at the end of the
// stream and break the loop, but it doesnt
while ((c = input.read()) != -1) {
sb.append((char) c);
}
serverDisplay(sb.toString());
}
} catch (IOException e) {
System.out.println("IO ex in the server");
}
For sending message on the client side I have the following code:
output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
and
private void sendMessage(String message) {
displayMessage(message);
try {
output.write(message);
output.flush();
} catch (IOException e) {
System.out.println("IO ex at sendMessage client");
}
}
It reads all the characters I send (from client to server; confirmed with Sys out) but when it is supposed to read the end of the stream (-1) it hangs there.
I have tried to print the "c" inside the while loop to see the value it returns and it simply doesn't go in the loop neither does it break it, it just hangs there.
I'm aware there are a few questions already related to this subject but I haven't found the solution to my problem in any of them.
Oddly enough (at least for me) if I use:
output = new ObjectOutputStream(connection.getOutputStream());
input = new ObjectInputStream(connection.getInputStream());
and:
while ((message = (String) input.readObject()) != null)
Instead of:
input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
And:
while ((c = input.read()) != -1)
The hole thing works. However this is not how I want to do it, and by reading the API's of the BufferedReader/Writer, Input/OutputStreamWriter I would think my code should work.
Thank you in advance.