I'm writing a small client application to communicate with a server. I open a socket between my client and the server and can read anything that goes out from the server with a BufferedReader. This is read in a thread. However, when I write on the socket using a BufferedReader, nothing happens ! No exception but not any server response (and it should have a server response) Here is my code:
socketWritter.write(message);
socketWritter.write("\n");
System.out.println(socketWritter.toString());
socketWritter.flush();
My socket is correctly open and mu BufferedWriter correctly initialized :
new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
I have no idea why this doesn't work ?? Any help would be great ! Regards
Your code is correct. I tested it with a generic server that will echo whatever the client sends and it worked fine (with no changes). It could be that the server your using is faulty. One thing I noticed was that for my server I needed to append a new line character every time I wrote to the output stream, for it to actually send the data. I'm willing to bet that's why your GUI isn't receiving anything. Here's the client thread class from my server:
class ClientThread extends Thread {
private Socket sock;
private InputStream in;
private OutputStream out;
ClientThread( Socket sock ) {
this.sock = sock;
try {
this.in = sock.getInputStream();
this.out = sock.getOutputStream();
} catch ( IOException e ) {
e.printStackTrace();
}
}
//Echos whatever the client sends to it
public void run() {
BufferedReader bufIn = new BufferedReader( new InputStreamReader( in ) );
BufferedWriter bufOut = new BufferedWriter( new OutputStreamWriter( out ) );
while ( true ) {
try {
String msg = bufIn.readLine();
System.out.println( "Received: " + msg );
bufOut.write( msg );
bufOut.newLine(); //HERE!!!!!!
bufOut.flush();
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
}