我在android上用socket-io。('com.github.nkzawa:socket.io-client:0.3.0')
在Nexus 10设备(Android4.2.1)上测试我的应用程序时,我发现在调用mSocket.connect()之后,libcore.net.http.HttpConnectionPool每12.7秒左右就创建一个libcore.net.http.HttpConnection对象。这会导致“太多打开的文件错误”,最终导致应用程序结冰或崩溃。
在调查泄漏时,我创建了一个空的android项目来重现泄漏。下面我只附加了一个空的"hello“项目上面添加的代码。
-code
添加到build.gradle依赖项中
compile 'com.github.nkzawa:socket.io-client:0.3.0'添加到Android声明中
<uses-permission android:name="android.permission.INTERNET" />主要活动..。
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
mSocket.connect();
}
private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
private Socket mSocket;
{
try
{
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, null);
IO.setDefaultSSLContext(sc);
HttpsURLConnection.setDefaultHostnameVerifier(new RelaxedHostNameVerifier());
mSocket = IO.socket("https://10.0.0.1");
mSocket.connect() ;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
catch (URISyntaxException e) {
e.printStackTrace();
}
}
public static class RelaxedHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}发布于 2016-05-03 18:19:55
好的。明白了。
经过一番挖掘,我在网上找到了这个。http://android-developers.blogspot.co.il/2011/09/androids-http-clients.html
总结一下。
“在Froyo之前,HttpURLConnection有一些令人沮丧的bug。特别是,在可读的InputStream上调用close()可能会毒害连接池。为此,禁用连接池:”
private void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}如前所述,我正在遭受果冻豆的泄漏,而不是弗罗约。我移除了条件。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.setProperty("http.keepAlive", "false") ;
...
}https://stackoverflow.com/questions/36960154
复制相似问题