SocketTimeoutException: Read time out

折月煮酒 提交于 2019-12-01 06:10:30

The problem is with the interaction between your use of BufferedReader.read() inside a while loop, and with the way you handle the socket from the other side of the connection.

..read() will only return -1 when the stream it is reading from has ended, which in this case will essentially mean that the socket is closed. Until the socket is closed, the server is just blocking on read, waiting for the client to send another character. As the server is blocking on read, it will never get to send 'pong' back. The client is blocking on its own read, but eventually your timeout is reached.

TCP sockets are for dealing with streams of data. If you want to use it to send discrete messages, you'll need to impose a protocol between the client and the server so that they each know when a complete message has arrived. In this case, the client and server can agree upon using a terminator character, to specify that a message is complete. For instance, they could agree to send a \n as a terminator after each message.

So, for example, in your client, the relevant code would look like:

writer.write("ping");
writer.write('\n');
writer.flush();

int i=0;
StringBuilder sb=new StringBuilder();
while((i=reader.read())!=-1){
    char c = (char)i;
    if(c == '\n')
        break;
    sb.append(c);
}
System.out.println("The server sends: "+sb);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!