user902383
user902383

Reputation: 8640

How to make socket communications?

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?

Upvotes: 1

Views: 50

Answers (1)

user207421
user207421

Reputation: 310893

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.

Upvotes: 3

Related Questions