BufferedReader readLine method hangs and block program

前端 未结 3 1216
说谎
说谎 2020-12-18 13:03

I\'m trying to learn sockets using Java and I sucessfully sent data to a ServerSocket running in my own machine. When I try to read from this socket using readline (so I can

相关标签:
3条回答
  • 2020-12-18 13:52

    The problem is that readLine tries reading a line. It will not return the line until it's sure that the end of line has been reached. This means that it expects either a newline character, or the end of the communication. Since the server doesn't send any newline char and doesn't close the stream, the client waits indefinitely.

    0 讨论(0)
  • 2020-12-18 13:54

    writeUTF() doesn't write a line. See the Javadoc. writeUTF() is for use with readUTF(). And Readers are for use with Writers. So change the DataOutputStream to a BufferedWriter and call write() and then newline().

    0 讨论(0)
  • 2020-12-18 14:03
    cli.ostream.writeUTF("Teste");
    

    Shouldn't this be containing a new line? Otherwise read method will be waiting for new line I think.

    Also as suggested you can try flushing the ostream after writing to it.

    0 讨论(0)
提交回复
热议问题