AndroidAsync icon indicating copy to clipboard operation
AndroidAsync copied to clipboard

How can I implement send-recv mode of tcp client socket

Open jflyup opened this issue 8 years ago • 1 comments

I'm writing a tcp client to connect multiple hosts asynchronously. After I called Util.writeAll, I want to call setDataCallback() after write completed, then write something when onDataAvailable callback completed, and so on. So I need a final AsyncSocket variable to be accessed from within inner class. Can I do so?

AsyncServer.getDefault().connectSocket(ip, port, new ConnectCallback() {
@Override
public void onConnectCompleted(Exception ex, AsyncSocket socket) {
    if (ex != null) {
        return;
    }
    Log.d("Async", "connected to " + ip);
    final AsyncSocket client = socket;
    Util.writeAll(client, req, new CompletedCallback() {
        @Override
        public void onCompleted(Exception ex) {
            if (ex != null)
            {
                Log.e("Async socket", "write failed with ex message= " + ex.getMessage());
                return;
            }
            Log.d("Async socket", "req sent");
            client.setDataCallback(new DataCallback() { // compiler error if no final keyword
                @Override
                public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                    Log.i("Async socket", "Data received: ");
                    ByteBuffer resp = bb.getAll();
                }
            });

        }
    });
}

jflyup avatar Jul 27 '17 16:07 jflyup

@jflyup I'm using your template for the same task - TCP client with AndroidAsync.

Have you answered your question? Is the way you posted correct?

dizcza avatar Oct 31 '22 17:10 dizcza