2013-04-24 143 views
3

我正在使用gottox socket.io java client进行Android聊天应用程序。
我可以连接到HTTP模式下的web-socket和Xhr传输。但是,当我切换到HTTPS只Xhr模式正在工作。我使用如下的默认SSL上下文Android Socket.io Websocket传输不适用于SSL

SocketIO.setDefaultSSLSocketFactory(SSLContext.getInstance("Default")); 

这在Xhr模式下正常工作。但在websocket传输中没有任何反应或错误。

+0

你可以分享你的代码,你如何改变传输到只有websocket – 2017-02-28 11:19:00

回答

0

带SSL的Websocket在AndroidAsync中工作。现在使用它。

1

它的工作原理,但你必须做一些修改io.socket库。 而不是使用socketio.jar,导入到src文件夹中的io.socket库(您会在socket.io-java-client包内找到)。在那里,你必须编辑WebsocketTransport类。

在这里,你有解决方案

https://github.com/Gottox/socket.io-java-client/issues/60

public WebsocketTransport(URI uri, IOConnection connection) { 
    super(uri); 
    this.connection = connection; 
    SSLContext context = null; 
    try { 
     context = SSLContext.getInstance("TLS", "HarmonyJSSE"); 
    } catch (NoSuchAlgorithmException e) { 
     e.printStackTrace(); 
    } catch (NoSuchProviderException e) { 
     e.printStackTrace(); 
    } 
    try { 
     context.init(null, null, null); 
    } catch (KeyManagementException e) { 
     e.printStackTrace(); 
    } 
    if("wss".equals(uri.getScheme()) && context != null) { 
     this.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(context)); 
    } 
} 

记住调用setDefaultSSLSocketFactory这样的:

socket = new SocketIO(); 
socket.setDefaultSSLSocketFactory(SSLContext.getDefault()); 
socket.connect("https://www.myHttpsServer.com:443/"); 

希望它可以帮助别人;)

0

我有与io.socket:socket.io-client:0.7.0版本相同的问题o f socket.io图书馆在Android上。它曾经为http协议工作正常,但是对于https协议,它在建立连接时遇到问题xhr poll errors

以下解决方案对我的作品,而无需修改库本身:

// Socket connection 
private Socket mSocket; 

// Configure options 
IO.Options options = new IO.Options(); 
// ... add more options 

// End point https 
String yourEndpoint = "https://whatever.yoururl.com" 
String yourHostName = "yoururl.com" 

// If https, explicitly tell set the sslContext. 
if (yourEndpoint.startsWith("https://")) {   
    try { 
     // Default settings for all sockets 

     // Set default ssl context 
     IO.setDefaultSSLContext(SSLContext.getDefault()); 

     // Set default hostname 
     HostnameVerifier hostnameVerifier = new HostnameVerifier() { 
      @Override 
      public boolean verify(String hostname, SSLSession session) { 
       HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 
       return hv.verify(yourHostName, session); 
      } 
     }; 
     IO.setDefaultHostnameVerifier(hostnameVerifier); 

     // set as an option 
     options.sslContext = SSLContext.getDefault(); 
     options.hostnameVerifier = hostnameVerifier; 
     options.secure = true; 

    } catch (NoSuchAlgorithmException e) { 
     e.printStackTrace(); 
    } 
} 

// Instantiate the socket 
mSocket = IO.socket(mEndpoint, options); 

希望这有助于。

+0

'IO.setDefaultSSLContext'和'IO。 setDefaultHostnameVerifier'在版本1.0中不再可用 – ffleandro 2017-09-13 19:14:47