我正在尝试开发一个将使用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 线程中使用的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?我不知道如何在调用onProgressUpdate
时更新 TextView。messageReceived
有什么建议吗?