如何检查WebSocket是否已连接

时间:2015-04-15 08:06:19

标签: java android performance websocket androidasync-koush

我使用KOUSH库https://github.com/koush/AndroidAsync#can-also-create-web-sockets

创建了一个Websocket服务类

现在我想检查Websocket是否从我的mainActivity连接到我的服务器。你知道我怎么检查这个吗? 谢谢

AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
    @Override
    public void onCompleted(Exception ex, WebSocket webSocket) {
        if (ex != null) {
            ex.printStackTrace();
            return;
        }
        webSocket.send("a string");
        webSocket.send(new byte[10]);
        webSocket.setStringCallback(new StringCallback() {
            public void onStringAvailable(String s) {
                System.out.println("I got a string: " + s);
            }
        });
        webSocket.setDataCallback(new DataCallback() {
            public void onDataAvailable(ByteBufferList byteBufferList) {
                System.out.println("I got some bytes!");
                // note that this data has been read
                byteBufferList.recycle();
            }
        });
    }
});

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

if (mWebSocketClient.isOpen) {
         mWebSocketClient.send(jObj.toString())
} else {
   try {
         client.connectWebSocket(p0)
         mWebSocketClient.send(jObj.toString())
   } catch (e : Exception){
        Toast.makeText(p0, "not connected $e", Toast.LENGTH_LONG).show()
   }
}

答案 1 :(得分:-1)

解决方案是将此函数的结果保存到本地Websocket变量,然后检查其状态:

WebSocket webSocket=null;
try {
    webSocket=AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
        @Override
        public void onCompleted(Exception ex, WebSocket webSocket) {
            if (ex != null) {
                ex.printStackTrace();
                return;
            }
            webSocket.send("a string");
            webSocket.send(new byte[10]);
            webSocket.setStringCallback(new StringCallback() {
                public void onStringAvailable(String s) {
                    System.out.println("I got a string: " + s);
                }
            });
            webSocket.setDataCallback(new DataCallback() {
                public void onDataAvailable(ByteBufferList byteBufferList) {
                    System.out.println("I got some bytes!");
                    // note that this data has been read
                    byteBufferList.recycle();
                }
            });
        }
    }).get();
}catch(InterruptedException e){
//handle exception 
}catch(ExecutionException e){
//handle exception
}

if(websocket!=null && websocket.isOpen()){
//websocket is working fine 
}

您可以使用其他语句,例如websocket.isClosed();