您的位置:首页 > 其它

netty concepts

2015-07-30 16:40 465 查看
这里主要想大致地理一下几个主要接口之间的关系,一旦理解,就变得直观,不然总是云里雾里。

下面是我的一个netty client的一段不完整的代码,在我电脑上是可以跑的,只是还有GZIP没有处理,看到的是乱码。

public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framer",
new DelimiterBasedFrameDecoder(8192,
Delimiters.lineDelimiter()));
// TODO GZIP and Data Length Session
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());

pipeline.addLast("handler", new FeedClientHandler());
}
});
ChannelFuture future = bootstrap.connect().sync();
future.channel().writeAndFlush(login);
Thread.sleep(60000); // todo
} finally {
group.shutdownGracefully();
}
}
先说说BootStrap,这个主要是抽象了process of configuring。

要启动一个网络客户端应用,我们应该为BootStrap配置些什么呢?

(1) 指定server端的IP和port,这样BootStrap就知道了数据要从什么地方拿。用的是remoteAddress方法。

(2) 指定是用哪种传输的通道,比如这里我们是用的NioSocketChannel,这样BootStrap就知道了要用Buffer去一批一批地拿数据,每拿到一批就触发一个事件。用的是channel方法。

(3) 注册事件组, register event loop with channel。这样我们在那个通道上就可以获得很多events。用的是group方法。

(4) 指定事件如何处理。用的是handler方法。对于流数据的处理,我们可能需要像流水线一样处理,于是netty抽象了ChannelPipeline接口,一个ChannelPipeline就包含了多个ChannelHandler,而怎么把这些ChannelHandler放到一个ChannelPipeline下呢,就用的是ChannelInitializer。BootStrap的handler方法实际不是指定一个ChannelHandler,而是一个ChannelHandler的集合。这样,我们看上面的代码就比较清晰了。

Reference:

[1] Netty in Action.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: