我想编写一个基于Netty的客户端。它应该有一个方法public String send(String msg);,该方法应返回来自服务器或某个未来的响应 - 不重要。此外,它应该是多线程的。像这样:
public class Client {
public static void main(String[] args) throws InterruptedException {
Client client = new Client();
}
private Channel channel;
public Client() throws InterruptedException {
EventLoopGroup loopGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(loopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder()).
addLast(new StringEncoder()).
addLast(new ClientHandler());
}
});
channel = b.connect("localhost", 9091).sync().channel();
}
public String sendMessage(String msg) {
channel.writeAndFlush(msg);
return ??????????;
}
}
我不明白在调用writeAndFlush()之后如何从服务器检索响应,我该怎么做?
另外,我使用的是Netty 4.0.18.Final版本。
channelActive
中分配ctx
是否保证被调用sendMessage(String)
的线程看到? - dnaultreturn sendMessage(message, ctx.newPromise());
中,newPromise 的类型是io.netty.channel.ChannelPromise
,但所需的类型是io.netty.util.concurrent.Promise<String>
。经过一些强制转换后,我得到了ClassCastException: java.lang.String cannot be cast to java.lang.Void
。 - Dawid Fielubactx.executor().newPromise()
而不是ctx.newPromise()
,我不确定旧代码第一次是如何编译的,可能是我使用了不同版本的Netty。 - Ferrybigctx.writeAndFlush(message).addListener();
实际上有什么作用(也许自从这篇文章写出来以后 API 就改变了,但是没有空的 addListener() 方法,而且这个分支对 Promise 没有任何影响。 :-( - cjstehno