文档章节

Netty关于Channel的使用的官方解释

Finley.Hamilton
 Finley.Hamilton
发布于 2014/11/11 10:27
字数 588
阅读 472
收藏 0
package io.netty.example.discard;

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Discards any incoming data.
 */
public class DiscardServer {

    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new DiscardServerHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new DiscardServer(port).run();
    }
}
  • NioEventLoopGroup is a multithreaded event loop that handles I/O operation. Netty provides various EventLoopGroup implementations for different kind of transports. We are implementing a server-side application in this example, and therefore two NioEventLoopGroup will be used. The first one, often called 'boss', accepts an incoming connection. The second one, often called 'worker', handles the traffic of the accepted connection once the boss accepts the connection and registers the accepted connection to the worker. How many Threads are used and how they are mapped to the created Channels depends on the EventLoopGroupimplementation and may be even configurable via a constructor.

  • ServerBootstrap is a helper class that sets up a server. You can set up the server using a Channel directly. However, please note that this is a tedious process, and you do not need to do that in most cases.

  • Here, we specify to use the NioServerSocketChannel class which is used to instantiate a new Channel to accept incoming connections.

  • The handler specified here will always be evaluated by a newly accepted Channel. The ChannelInitializer is a special handler that is purposed to help a user configure a new Channel. It is most likely that you want to configure the ChannelPipeline of the new Channel by adding some handlers such as DiscardServerHandlerto implement your network application. As the application gets complicated, it is likely that you will add more handlers to the pipeline and extract this anonymous class into a top level class eventually.

  • You can also set the parameters which are specific to the Channel implementation. We are writing a TCP/IP server, so we are allowed to set the socket options such as tcpNoDelay and keepAlive. Please refer to the apidocs of ChannelOption and the specific ChannelConfig implementations to get an overview about the supported ChannelOptions.

  • Did you notice option() and childOption()? option() is for the NioServerSocketChannel that accepts incoming connections. childOption() is for the Channels accepted by the parent ServerChannel, which is NioServerSocketChannel in this case.

  • We are ready to go now. What's left is to bind to the port and to start the server. Here, we bind to the port 8080 of all NICs (network interface cards) in the machine. You can now call the bind() method as many times as you want (with different bind addresses.

这段程序可以用Telnet去测试

本文转载自:http://netty.io/wiki/user-guide-for-5.x.html

共有 人打赏支持
Finley.Hamilton

Finley.Hamilton

粉丝 5
博文 45
码字总数 15431
作品 0
广州
私信 提问
netty源码分析之揭开reactor线程的面纱(二)

如果你对netty的reactor线程不了解,建议先看下上一篇文章netty源码分析之揭开reactor线程的面纱(一),这里再把reactor中的三个步骤的图贴一下 我们已经了解到netty reactor线程的第一步是...

闪电侠_
08/02
0
0
netty源码分析之服务端启动全解析

background netty 是一个异步事件驱动的网络通信层框架,其官方文档的解释为 Netty is a NIO client server framework which enables quick and easy development of network applications ......

️闪电侠
05/29
0
0
Netty5.x中新增和值得注意的点

翻译自官方文档:http://netty.io/wiki/new-and-noteworthy-in-5.x.html 该文档会列出在Netty新版本中值得注意变化和新特性列表。帮助你的应用更好的适应新的版本。 不像Netty3.x和4.x之间的...

JavaGG
2014/06/20
0
0
netty文章收藏

1.林峰的关于netty文章 不错,遇到问题反复看了几遍总有启发,还说收藏记录一下。 http://www.infoq.com/cn/netty Netty案例集锦之多线程篇(续)作者 李林锋 发布于 2015年11月25日 9 Nett...

GREKI
2016/04/05
604
0
Netty5.x中新增和值得注意的点

支持Android 提供了: 移动设备变成更加强大 通过Ice Cream Sandwich解决了在ADK中最著名的与NIO和SSLEngine相关的问题,且 用户显然想要重用他们应用中的的编解码和处理器代码。 我们决定官...

天下杰论
2014/08/08
0
0

没有更多内容

加载失败,请刷新页面

加载更多

tomcat线程模型

Connector结构 BIO模式 NIO模式

grace_233
23分钟前
1
0
Javascript

变量定义 以$,_,字母开头 大小写敏感 var 关键字声明变量 声明未赋值undefined 数据类型 字符串,数字,布尔,数组,NULL,undefined 变量均为对象 函数 无默认值 var声明的是局部变量 函数外声明...

关元
25分钟前
1
0
文件系统、服务、防火墙、SELINUX——安全四大金刚

一提到安全,大家都会想到防火墙,和文件系统权限。而实际工作环境中,我们在Linux的安全配置,会涉及到四个级别。我们思考一个场景,你要在百度盘中存放一个文件,这个动作需要考虑下面四个...

Linux就该这么学
26分钟前
1
0
从源码角度理解Java设计模式——门面模式

一、门面模式介绍 门面模式定义:也叫外观模式,定义了一个访问子系统的接口,除了这个接口以外,不允许其他访问子系统的行为发生。 适用场景:子系统很复杂时,增加一个接口供外部访问。 优...

我叫刘半仙
35分钟前
2
0
新鲜出炉,2019最新大厂面试题总汇!

在这个互联网技术快速迭代的时代,每个程序员都知道技术对于职业发展的重要性,那些技术好的程序员不仅薪资高,而且大多数集中在一线互联网企业工作,让人感觉非常高大上的同时,也想去大厂做...

Java架构资源分享
44分钟前
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部