为什么SocketChannel调用read(byteBuffer)抛出java.net.SocketException:recvfrom失败:ECONNRESET(由对等方重置连接)

时间:2017-05-17 06:54:28

标签: java android nio socketchannel econnreset

我们的项目实现了基于NIO for push的自己的长连接框架,它曾经正常工作。最近,有一些问题,“SocketChannel.read(byteBuffer)”抛出异常“java.net.SocketException:recvfrom failed:ECONNRESET(Connection peer by peer)”,详细信息如下: enter image description here

图片包含错误消息

错误代码如下:

private void read(ByteBuffer byteBuffer, int length) throws Exception {
        int count = 0;
        long readBeginMills = SystemClock.elapsedRealtime();
        while (count < length) {
            try {
                int readCount = mSocketChannel.read(byteBuffer);
                long nowMills = SystemClock.elapsedRealtime();
                if (readCount > 0) {
                    count += readCount;
                    readBeginMills = nowMills;
                }
                //1.readCount为-1时是连接断开了,直接报错重连
                //2.如果读取数据超过了20s也报错重连
                if(nowMills - readBeginMills >= 20000 || readCount == -1){
                    throw new LostTcpByteException("byte lost exception,need to shutdown and reconnection");
                }
            } catch (Exception e) {
                throw e;
            }
        }
    }
我找了很多类似的错误,但没有找到解决问题的好主意,我该怎么办? 谢谢你的任何一个人!

1 个答案:

答案 0 :(得分:3)

或者:

  1. 您已将数据发送到已由对等方关闭的连接
  2. 对等体在其套接字接收缓冲区中仍有未读数据时关闭了连接
  3. 对等体正在Windows上运行,其进程已退出。
  4. 对等方故意通过我不在此详述的方式重置连接。
  5. 出现了各种主机或网络状况之一,例如连接超时或故障。
相关问题