4

我使用 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();
            }
        });
    }
});
4

2 回答 2

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()
   }
}
于 2019-08-02T13:26:58.857 回答
-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();

于 2017-06-13T23:33:02.347 回答