`

Practical Netty (4) 父子频道关系,频道与管道的关系

 
阅读更多

Practical Netty (4) 父子频道关系,频道与管道的关系


(下面这段话是完成本文后写的)我姑且将 Parent channel 称为父频道,Child Channel 称为子频道,Channel 就是频道了,而 ChannelPipeline 则称为管道。这样的目的只有一个,就是能在 CSDN 博客里把标题弄短一点。。。当然了,下文中仍然用了英文名称,因为上面这几个中文名称是我写完本文后回头起标题的时候,为了缩短才搞的,哈哈。

1. Netty 核心概念之三:Parent Channel 与 Child Channels

一个 ServerBootstrap 启动后,会创建一个 parent channel,这个 parent channel 用于接受 connections,每个 connection 会被分配到一个 child channel 上,用于后续的处理。

Parent channel 和 child channels 的 options 是由 ServerBootstrap 来设置的。可设置的 key 和 value type 如下:

  • "localAddress"InetSocketAddress
  • "keepAlive"boolean
  • "reuseAddress"boolean
  • "soLinger"int
  • "tcpNoDelay"boolean
  • "receiveBufferSize"int
  • "sendBufferSize"int
  • "trafficClass"int

一段示例代码:

bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("localAddress", new InetSocketAddress(port));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.receiveBufferSize", 1048576);

转载请注明来自柳大的CSDN博客:Blog.CSDN.net/Poechant,微博:weibo.com/lauginhom

2. Netty 核心概念之四:Channel 与 ChannelPipeline

先看 Netty 官方文档的一段话:

For each new channel, a new pipeline must be created and attached to the
channel. Once attached, the coupling between the channel and the pipeline
is permanent; the channel cannot attach another pipeline to it nor detach
the current pipeline from it.

每个 Channel 都有对应的一个 ChannelPipe,而且必须有。对于一个 Bootstrap,你需要指定它的 ChannelPipeline 如何产生,这通过:

bootstrap.setPipelineFactory(ChannelPipelineFactory factory);

来实现。ChannelPipelineFactory是一个Interface,所以你需要implements它,举例如下:

bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    ChannelPipeline p = Channels.pipeline();
    p.addLast("handler", new PoechantProxyHandler());
});

这是一个匿名类的实现方式,实名类你也应该懂的。官方那段话告诉我们,你给一个 Channel 只能 attach 一个 ChannelPipeline,而且一旦 attach 就不能 detach 了,这也就是为什么会有一个 setPipelineFactory 的东东的原因,它来定义给你的 Channel 绑定 ChannelPipeline 的规则(包括什么样的 ChannelPipeline)。

-

转载请注明来自柳大的CSDN博客:Blog.CSDN.net/Poechant,微博:weibo.com/lauginhom

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics