https:// websocket没有连接android

时间:2016-09-27 07:39:56

标签: java android websocket

我有连接套接字http://(with port)网址已完成并正常工作,但我已连接https://(without port)无法在Java-WebSocket中工作。

我使用gradle依赖'org.java-websocket:Java-WebSocket:1.3.0'

WebSocketClient   mWebSocketClient = new WebSocketClient(uri) {
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        Log.e(TAG, "Websocket: " + "Opened");
        mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
    }

    @Override
    public void connect() {
        super.connect();
        //Log.e(TAG, "Websocket: " + "connect");
        SharedPreference.storeValue(mContext, SharedPreference.WEB_SOCKET_STATUS, SharedPreference.WEB_SOCKET_CONNECT);
    }
}

3 个答案:

答案 0 :(得分:2)

我找到了解决方案!)如果你想使用 wss:// ,你应该设置 setWebSocketFactory ..就像这样:

public void connect() {

    final String url = "wss://echo.websocket.org";
    URI uri=null;
    try{
        uri = new URI(url);
    }
    catch (URISyntaxException e) 
    {
        Log.e(TAG, e.getMessage());
        return;
    }
    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake handshakedata) {
            Log.e(TAG,"Connected!");
        }

        @Override
        public void onMessage(String message) {
            Log.e(TAG,"Message: "+message);

        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            Log.e(TAG,"Disconnected!");

        }

        @Override
        public void onError(Exception ex) {
            Log.e(TAG,"Error: "+ex.getMessage());

        }
    };

    if (url.indexOf("wss") == 0) {
        try {
            SSLContext sslContext = SSLContext.getDefault();
            mWebSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    mWebSocketClient.connect();
}

答案 1 :(得分:1)

检查清单:

<uses-permission android:name="android.permission.INTERNET" >
 </uses-permission>

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >  
</uses-permission

请发布Log Cat!

答案 2 :(得分:0)

Websocket有自己的协议ws://wss://(类似于http://https://),尝试使用这些协议。