Socket : Connection reset的解决方案

时间:2025-03-08 08:57:46

背景:
服务端通讯方式:TCP/IP socket 短链接。
首先看下我的最开始的socket代码:

public static byte[] sendMessage(String url, int port, byte[] request, int timeout) {
        byte[] res = null;
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            socket = new Socket(url, port);
            (timeout);
            is = ();
            os = ();
            (request);
            ();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int count;
            while ((count = (buffer)) != -1) {
                (buffer, 0, count);
            }
            res = ();
        } catch (Exception ex) {
            ();
        } finally {
            try {
                if (os != null) {
                    ();
                }
                if (is != null) {
                    ();
                }
                if (socket != null) {
                    ();
                }
            } catch (Exception e) {
                ();
            }

        }
        return res;
    }

上面这段代码,是最常用的的socket 发送方式,对于一般的socket链接都适用。但是在这里跟银行联调时一直报了一个错:
: Connection reset
at (:196)
at (:122)
at (:108)
经查阅问题描述如下:
1,如果一端的Socket被关闭(或主动关闭,或因为异常退出而 引起的关闭),另一端仍发送数据,发送的第一个数据包引发该异常(Connect reset by peer)。

2,一端退出,但退出时并未关闭该连接,另一端如果在从连接中读数据则抛出该异常(Connection reset)。简单的说就是在连接断开后的读和写操作引起的。

我这里是客户端,socket最后关闭,原因只能是2。说明对方在把数据返回后,就把socket关闭了,而客户端还在读数据。所以就connection reset。

解决方案;
使用判定是否还有可读字节
available()
返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。
如下:

 public static byte[] sendMessage(String url, int port, byte[] request) {
        byte[] res = null;
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            socket = new Socket(url, port);
            os = ();
            (request);
            ();
            is = ();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            do {
                count = (buffer);
                (buffer, 0, count);
            } while (() != 0);
            res = ();
            ();
            ();
            ();
        } catch (Exception ex) {
            try {
                if (is != null) {
                    ();
                }
                if (socket != null)
                    ();
            } catch (Exception e) {
            }
        }
        return res;
    }