您的位置:首页 > 理论基础 > 计算机网络

Android网络多次连接测试,网络正常时出现连接超时失败

2015-05-26 15:46 423 查看
修改前:

public boolean testTcp() {

        boolean ret = false;

        if (mRouterIp == null || mRouterIp.length() < 10) {

            Log.e(TAG, "hecong mRouterIp == Null or .length < 10");

            return ret;

        }

        Socket socket = new Socket();

        try {

            socket.setKeepAlive(true);

            socket.setTcpNoDelay(true);

            socket.connect(new InetSocketAddress(mRouterIp, 80), 2000);

        } catch (SocketException e1) {

            // TODO Auto-generated catch block
            Log.e(TAG, " e1 SocketException");

            e1.printStackTrace();

            return ret; 

        } catch (IOException e) {

            Log.e(TAG, "e2 SocketException");

            // TODO Auto-generated catch block
            e.printStackTrace();

            return ret;

        }

        

    

        try {

            socket.close();

        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();

        }
       return true; 

}
//推测为socket在网络不好时,没有关闭,影响连接.

修改后:
public boolean testTcp() {

        boolean ret = false;

        if (mRouterIp == null || mRouterIp.length() < 10) {

            Log.e(TAG, "hecong mRouterIp == Null or .length < 10");

            return ret;

        }

        Socket socket = new Socket();

        try {

            socket.setKeepAlive(true);

            socket.setTcpNoDelay(true);

            socket.connect(new InetSocketAddress(mRouterIp, 80), 2000);

            ret = true;

        } catch (SocketException e1) {

            // TODO Auto-generated catch block
            Log.e(TAG, " e1 SocketException");

            e1.printStackTrace();

            ret = false;  

        } catch (IOException e) {

            Log.e(TAG, "e2 SocketException");

            // TODO Auto-generated catch block
            e.printStackTrace();

            ret = false;

        }

        

    

        try {

            if(socket != null )socket.close();

        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();

        }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐