1

Recently I was looking at socket communications, and after I read few tutorials I came out with something like that.

public class Server{ public static void main(String[] args) throws IOException, InterruptedException { ServerSocket server = new ServerSocket(9999); Socket socket = server.accept(); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String message = ""; int ch = -1; while((ch=in.read())!= -1 ){ message+=ch; } // String message = in.readLine(); System.out.println("RECEIVED "+message); out.write("RESPONSE "+message+"\n"); out.flush(); System.out.println("NEW MESSAGE SEND"); Thread.sleep(3000); System.out.println("CLOSE"); server.close(); } } 

public class Client { public static void main(String[] args) throws UnknownHostException, IOException { Socket socket = new Socket("127.0.0.1", 9999); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.write("MESSAGE\n"); out.flush(); System.out.println("SEND MESSAGE"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(in.readLine()); socket.close(); } } 

After I run this code, Client logs "SEND MESSAGE" while server hangs on in.read() and does not receiving any message. Can anyone help me and explain me what I'm doing wrong?

3
  • 2
    Did you follow the official tutorial? Commented Feb 17, 2016 at 23:14
  • @GermannArlington Yes he does. Otherwise he can't wrap a BufferedReader around it. Commented Feb 17, 2016 at 23:18
  • @GermannArlington That's wrong. BufferedReader does not take an InputStream as argument. Commented Feb 17, 2016 at 23:18

1 Answer 1

3

Your server is reading from the socket until end of stream. End of stream only occurs when the peer closes the connection. At that point you will be unable to send a reply. You need to reconsider your protocol. For a simple example you could read and write lines, one at a time, as you are in the client.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm accepting your answer as it gave me hint, and some ideas what is happening, but actually using method println instead write solve my problem.
Actually there is no difference between write("MESSAGE\n") and println("MESSAGE"), and actually your problem was that you were reading the input until end of stream instead of a line at a time.
you are right, i just looked at implementation, maybe i did something else, it was too late yesterday. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.