Netty 框架或如何将其与 AsyncTask 一起使用



我正在尝试开发一个将使用Netty的Android应用程序。

首先,我想在Android上测试Netty,所以我将开发EchoClient示例。

我正在"翻译"客户部分。这部分有两个类:EchoClient 和 EchoClientHandler

EchoClient作为线程运行,EchoClientHandler处理所有网络内容。

在 main 方法上,EchoClient 像这样运行:

new EchoClient(host, port, firstMessageSize).run();

EchoClientHandler使用异步事件编程模型。

以下是一段EchoClient的代码:

public void run() {
    // Configure the client.
    ClientBootstrap bootstrap = new ClientBootstrap(
            new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));
    // Set up the pipeline factory.
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(
                    new EchoClientHandler(firstMessageSize));
        }
    });
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection is closed or the connection attempt fails.
    future.getChannel().getCloseFuture().awaitUninterruptibly();
    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
}

这种run()方法可以是AsyncTask.doBackground()方法。

如您所见,EchoClientHandler 是此类的一部分。

这是我想在UI Thread中使用的EchoClientHandler方法:

@Override
public void messageReceived(
        ChannelHandlerContext ctx, MessageEvent e) {
    // Send back the received message to the remote peer.
    transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
    e.getChannel().write(e.getMessage());
}

如何在AsynTask中使用EchoClientHandler?我不知道如何在调用messageReceived时更新onProgressUpdate上的文本视图。

有什么建议吗?

也许你可以使用回调。

第 1 步。定义接口

public interface MyCallback {
     public void onMessage(string msg);
}

第 2 步。在 EchoHandler 构造函数中获取符合该接口的对象,并将其存储为类变量

private MyCallback _myCallback
public EchoClientHandler(int firstMessageSize, MyCallback callback) {
   _myCallback = myCallback;
   ...
}

第 3 步。将对象传递给管道中的该构造函数。myCallback 可以来自 run() 作为参数,也可以来自 EchoClient 构造函数。

// Set up the pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    public ChannelPipeline getPipeline() throws Exception {
        return Channels.pipeline(
                new EchoClientHandler(firstMessageSize, myCallback));
    }
})

第 4 步。在消息处理程序中调用回调

@Override
public void messageReceived(
    ChannelHandlerContext ctx, MessageEvent e) {
    // Send back the received message to the remote peer.
    transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
    e.getChannel().write(e.getMessage());
    _myCallback.onMessage("message");
}

希望这有帮助。

最新更新