Socket, BufferedReader hangs at readLine()

后端 未结 4 1201
广开言路
广开言路 2020-12-08 07:52

I have a server which initially does this:-

BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
for (;;) {
  String cmdLine =          


        
4条回答
  •  生来不讨喜
    2020-12-08 08:24

    I had the same problem and here is my solution:

    try {
        StringBuilder response = new StringBuilder();
        response.append("SERVER -> CLIENT message:").append(CRLF);
        //Infinite loop
        while (true) {
            //Checks wheather the stream is ready
            if (in.ready()) {
                //Actually read line 
                lastLineFromServer = in.readLine();
                //If we have normal behavior at the end of stream
                if (lastLineFromServer != null) {
                    response
                            .append(lastLineFromServer)
                            .append(CRLF);
                } else {
                    return response.toString();
                }
            } else {//If stream is not ready
                //If number of tries is not exceeded
                if (numberOfTry < MAX_NUMBER_OF_TRIES) {
                    numberOfTry++;
                    //Wait for stream to become ready
                    Thread.sleep(MAX_DELAY_BEFORE_NEXT_TRY);
                } else {//If number of tries is exeeded
                    //Adds warning that things go weired
                    response
                            .append("WARNING \r\n")
                            .append("Server sends responses not poroperly.\r\n")
                            .append("Response might be incomplete.")
                            .append(CRLF);
                    return response.toString();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return "";
    }
    

提交回复
热议问题