I'm doing a chat application between mulitples clients in C# who connects a single Java Server.
So I send a message by one of users to the server, and the server sends this message to all others connected users.
Each client has a different Thread in the server, and in the thread I have;
public class ServerThread extends Thread {
private Server server;
private Socket sck;
InputStream receive;
OutputStream send;
public ServerThread(Server server, Socket s) {
this.server = server;
sck = s;
}
public void run() {
try {
handleClient();
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleClient() throws IOException {
receive = sck.getInputStream();
send = sck.getOutputStream();
byte[] b = new byte[1024];
receive.read(b);
System.out.print(new String(b));
BufferedReader reader = new BufferedReader(new InputStreamReader(receive, "UTF-8"));
String line;
while((line = reader.readLine()) != null) {
if(line.equalsIgnoreCase("quit"))break;
List<ServerThread> clients = server.getClients();
for(ServerThread allClients : clients) {
allClients.send(line);
}
}
}
private void send(String message) {
try {
send.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
And my problem is:
when a client send something to the server, I can read it with;
byte[] b = new byte[1024];
receive.read(b);
System.out.print(new String(b));
I get the correct String I sent, but the BufferedReader doesnt receive anything. The program never goes into the while loop because
line = reader.readLine();
doesnt read anything, so I dont have any idea what's wrong. Why "InputStream#read(byte)" works but "BufferedReader#readLine()" doesnt work.. ?
Here is what I send by the C# app;
byte[] text = System.Text.Encoding.UTF-8.GetBytes("test1212");
sck.Send(text);
Is something wrong with this message? :v
EDIT: Even with "\r\n" at the end of the message I send the Buffered doesnt read it.. How i'm supposed to add the carriage return to the message?
Hope somebody find what's wrong.
Thanks for trying to help me. (Sorry if i made mistakes, I'm French :l)
Read javadoc: BufferedReader.readLine()
"... Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. ..."
Your line does not have end of line. BufferedReader waits for it.