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

修改前:

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();
        
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值