java.net.sockettimeoutexception: read timed out的问题

client有如下伪代码:

try{
    Socket ss = new Socket();
    ss.connect(new InetSocketAddress(127.0.0.1, TCPServer.LISTEN_PORT), 4000);
    ss.setSoTimeout(5000);
    
    //dosomthing
    InputStream is = ss.getInputStrean();
    log.info("read start time:" + System.currentTimeMillis())
    int r = is.read(....);
    log.info("read start time:" + System.currentTimeMillis())
} catch(Exception e){
    log.info("throw exception time:" + System.currentTimeMillis());
}

上面这样的逻辑,ss.setSoTimeout(5000);把读超时设置为5000ms,可经过测试read的时间也不过才619ms 就抛出了如题的异常?

阅读 16k
2 个回答

这是服务端是同步通知,时间过长,把服务端修改成异步的即可

这个timeout,并不是触发的你setSoTimeOut(5000)的异常。我的理解是soTimeOut是整个Socket建立连接的最长超时时间,如果你之前connect 没有TimeOut,Read 没有TimeOut,Write 也没有TimeOut,但是你的socket仍然没有得到关闭,当时间超过SoTimeOut的时候,就会抛出异常。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题