Socket problem - readline won't work properly

后端 未结 5 1278
灰色年华
灰色年华 2020-12-11 13:09

I try to code a client and server connection using socket. The problem is my client can\'t read the response from the server (it hangs on the readline).

Here is some

5条回答
  •  我在风中等你
    2020-12-11 13:14

    OK, I made several editing in the code and now it run nicely :

    The server :

        try {
            // Create the server socket.
            portNumber = Integer.parseInt(myParam.get("socket.portNumber"));
            mainSocket = new ServerSocket(portNumber);
    
        } catch (IOException ioe) {
            System.out.println("Error Message : " + ioe.getMessage());
        }
    
        // Accept connections    
        try {
            clientSocket = mainSocket.accept();
        } catch (IOException ioe) {
            System.out.println("Error Message : " + ioe.getMessage());
        }
        BufferedReader in = null;
        PrintWriter out = null;
    
        while (true) {
            try {
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                //Read The Message
                **StringBuffer buffer = new StringBuffer();
                while (true) {
                    int ch = in.read();
                    if ((ch < 0) || (ch == '\n')) {
                        break;
                    }
                    buffer.append((char) ch);
                }
                String clientRequest = buffer.toString();**
    
                SocketServerThread st = new SocketServerThread(clientRequest, out);
                st.start();
            } catch (IOException ioe) {
                System.out.println("Can't accept connection. Error message :" + ioe.getMessage());
            }
        }
    

    I change the readline with read and it work, so the assumption that "\n" is the problem is correct.

    The thread : a minor change in the thread (remove the reading request part since I already done that in the server)

    The Client: change the readline into read just like the server one.

    Thank you all for the help

提交回复
热议问题