[英]How to check if WebSocket is connected
我使用KOUSH庫創建了一個Websocket服務類https://github.com/koush/AndroidAsync#can-also-create-web-sockets
現在我想檢查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();
}
});
}
});
你可以這樣做:
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()
}
}
解決方案是將此函數的結果保存到本地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()等其他語句;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.