我正在尝试通过websocket发送数据并接收相同的回声。当我尝试通过后台线程发送它时,我没有收到回音。可能有什么不对?通过后台线程发送数据是否不正确?如果是这样,为什么?
请检查我的代码以及随附的相关日志。
private final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(final WebSocket webSocket, Response response) {
class SendData extends AsyncTask {
@Override
protected void onPreExecute(){
Log.d("Websocket","In Pre-execute");
webSocket.send("In pre-execute");
}
@Override
protected Object doInBackground(Object[] objects) {
Log.d("AsyncTask","In doInBackground");
//The below statement receives no echo
webSocket.send("doInBackground");
Log.d("AsyncTask","In END of doInBackground");
return null;
}
}
new SendData().execute();
webSocket.send(ByteString.decodeHex("1245"));
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
Log.i("Receiving : ",text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
Log.i("Receiving bytes : " , bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
Log.i("Closing : " , code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
Log.i("Error", "Error in WebsocketEcho");
}
}
日志:
D/AsyncTask: In Pre-execute
D/AsyncTask: In doInBackground
D/AsyncTask: In END of doInBackground
I/Receiving :: In pre-execute
I/Receiving bytes :: 1245
I/Closing :: 1000 / Goodbye !
答案 0 :(得分:0)
完成关闭线程时的异步任务。因此完成AsyncTask时关闭套接字的线程。从asyncTask中使用你的套接字然后它将工作。有关详细信息,请参阅执行异步任务和threadpoolexecutor。
您可以在此处找到更多详细信息:
https://developer.android.com/reference/android/os/AsyncTask.html