简体   繁体   中英

Java Socket Client not Recieving Data

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.

我找到了解决方案:我需要在行尾添加一个 '\\n' 以使 BufferedReader 的 DataOutputStream/PrintWriter 正常工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM