The following code works ,the server gets the com
string and then the connection closes,if I uncomment the bw.flush()
and its next line ,The server doesn't get the com string anymore and it just waits on the br.readLine()
for a response(which will not get since the server didn't got the com string),if I move the bw.close()
and put it in the bw.flush()
position the br.readLine()
will throw a Socket closed exception.
public static void setupClient(String[] args) throws UnknownHostException, IOException{
Socket client = new Socket(InetAddress.getLocalHost().getHostName(), Server.DEFAULT_COMMAND_PORT);
BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader br =new BufferedReader(new InputStreamReader(client.getInputStream()));
String com=args[0]+(args.length==2?args[1]:"");
bw.write(com);
// bw.flush();
// System.out.println("response:"+br.readLine());
bw.close();
client.close();
}
You are reading lines but you aren't writing lines. readLine()
returns when it reads a line terminator or end of stream. That's why it works when the peer closes instead of flushing. You need to use BufferedWriter.newLine()
after your write().