3

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

首先我想在 Android 上测试 Netty,所以我要开发EchoClient的例子。

我正在“翻译”客户部分。这部分有两个类:EchoClientEchoClientHandler

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

有什么建议吗?

4

1 回答 1

0

也许你可以使用回调。

步骤 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");
}

希望这可以帮助。

于 2012-06-10T23:48:39.013 回答