Socket problem - readline won't work properly

后端 未结 5 1282
灰色年华
灰色年华 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:24

    out.write("My message");
    

    That doesn't send a line terminator so it can never be read. Use println().

    out.println(clientResponse+"\n");
    

    That will send the clientResponse plus a newline plus a \n. The last part will probably be interpreted as a blank line. Not much point in that. Remove the \n.

    do{
        response = in.readLine(); //This is where the code hang
    }while (response.length()<= 0);
    

    That's not the correct way to read lines. It will get an NPE at EOS; the response length can never be negative; and why would you send yourself blank lines? The correct way is this:

    while ((response = in.readLine()) != null) {
        // if (response.length() == 0) continue; // if you must
        // process the line
    }
    // when you get here EOS has occurred.
    

提交回复
热议问题