-2

I have created my first test application implementing a socket server. I am having some issues getting the client to receive data, but the server gets data just fine. Here is the server:

ServerSocket socket = new ServerSocket(11111);
                System.out.println("CREATING SERVER...");
                while (true) {
                    Socket SERVER_WORK = socket.accept();
                    BufferedReader clientIN = new BufferedReader(new InputStreamReader(SERVER_WORK.getInputStream()));
                    PrintWriter outSend = new PrintWriter(SERVER_WORK.getOutputStream());
                    String ClientSTR = clientIN.readLine();
                    System.out.println("Client 1: " + ClientSTR);
                    String toClient = "Hello";
                    outSend.write(toClient + '\n');
                }

And here is the client:

System.out.println("CONNECTING TO SERVER...");
                while (true) {
                    Socket clientSocket = new Socket(server, 11111);
                    BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    DataOutputStream toServere = new DataOutputStream(clientSocket.getOutputStream());
                    Scanner in = new Scanner(System.in);
                    toServere.write(in.nextLine().getBytes());
                    if (fromServer.ready())
                    System.out.println(fromServer.readLine());
                    clientSocket.close();
                }

Everything works properly except for the client receiving data.

campital
  • 36
  • 8
  • 1
    Try, `outSend.flush()` on the server to make sure that the bytes were actually sent instead of held in the buffer. http://stackoverflow.com/questions/2340106/what-is-the-purpose-of-flush-in-java-streams – ug_ Feb 12 '17 at 04:54
  • 1
    Your 'server' is a client, and your 'client' is a server. The first piece of code never closes the socket. The `ready()` call is pointless and should be removed. You are reading lines in the first piece of code but you aren't sending lines in the second piece of code. – user207421 Feb 12 '17 at 04:55

1 Answers1

-1

I found the solution: I needed a '\n' at the end of the line for the DataOutputStream/PrintWriter for the BufferedReader to work properly.

campital
  • 36
  • 8