I have made a java ServerSocket. I send a request to it using a Socket Object. The request is delivered to the ServerSocket but the response does not come back.
Server Code :
Socket startserver = this.wifiserver.accept();
in = new InputStreamReader(startserver.getInputStream());
BufferedReader read = new BufferedReader(in);
String request = read.readLine();
//System.out.println(request);
if(request.equals("SNDKEY")){
System.out.println("Command is: SNDKEY");
out = new PrintWriter(startserver.getOutputStream());
out.print("12345678901234567890");
out.close();
}
Client Code:
Socket connection = new Socket( ip, port );
writeServer = new PrintWriter(connection.getOutputStream());
inputStream = new InputStreamReader(connection.getInputStream());
bufferStream = new BufferedReader(inputStream);
writeServer.print("SNDKEY");
this.Key = bufferStream.readLine();
The problem is that the program gets stuck at the command bufferStream.readLine(). I have checked that the request is reaching the server by outputing the line command is: SNDKEY and it always gets printing out. But the key is never received at the user end.
bufferStream.readLine()blocks until a newline is received. But on the server side you are outputting withPrintWriter.print(), which doesn’t send any newlines unless you tell it to. So the client waits forever. Either change the print to println, or add a newline character to the end of the message:When you don’t want to use newlines in your protocol, you could alternatively use
bufferStream.readinstead ofbufferStream.readLineto return after reading each byte or after reading a specific number of bytes.