Cannot send and receive data using BufferedReader/Writer on sockets

亡梦爱人 提交于 2019-12-02 01:08:37

You are suffering from buffering: message is written in a buffer and probably never sent. Flush the writer to ensure it sends data:

    writer.write(...);
    writer.flush();

Also, BufferedReader.readLine reads lines. Lines have to be terminated with a line break, such as \n. It's not clear if you are sending line breaks.

Also, this is an infinite loop:

    String message=input.readLine();
    while(message.length()!=0) {
        /* code that does not modify message */
    }

Don't keep creating new readers and writers. Use the same ones for the life of the socket. You're losing data in the old BufferedReader that is being discarded. These buffered things, err, buffer.

Also this:

String message=input.readLine();
while(message.length()!=0)

is, err, nonsense. Firstly you're not checking message for null, so you're going to get a NullPointerException at end of stream. Secondly, you aren't doing any further input inside the loop so if it doesn't throw NPE and the message isn't zero length it will loop forever.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!