首页 > 代码库 > Java Netty (1)

Java Netty (1)

Netty是由JBOSS提供的一个java开源框架,本质上也是NIO,是对NIO的封装,比NIO更加高级,可以说发展的路线是IO->NIO->Netty。

ServerBootstrap和ClientBootstrap是Netty中两个比较重要的类,分别用来进行服务器和客户端的初始化。

服务器:

        // ChannelFactory        final ChannelFactory channelFactory = new NioServerSocketChannelFactory(                  // Boss线程池,处理Socket请求                Executors.newCachedThreadPool(),                  // Worker线程池,由于使用的是NIO,1个Worker线程可以管理多个Channel                Executors.newCachedThreadPool());         // ServerBootstrap        ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);            ServerPipelineFactory serverPipelineFactory = new ServerPipelineFactory(executionHandler);        bootstrap.setPipelineFactory(serverPipelineFactory); 

ServerBootstrap实例化时需要一个ServerSocketChannelFactory参数,ServerSocketChannelFactory可以选择NioServerSocketChannelFactory

或者OioServerSocketChannelFactory,NioServerSocketChannelFactory使用的是NIO,OioServerSocketChannelFactory使用的是普通IO。两者都需要两个线程池,一个Boss线程池,一个Worker线程池。一个Boss线程负责对一个端口的监听,接收到Socket连接请求以后交给一个Worker线程处理,然后自己继续监听。

客户端:

        // ChannelFactory        final ChannelFactory channelFactory = new NioClientSocketChannelFactory(                  // Boss线程池                Executors.newCachedThreadPool(),                  // Worker线程池                Executors.newCachedThreadPool());          // ServerBootstrap        bootstrap = new ClientBootstrap(channelFactory);                ClientPipelineFactory clientPipelineFactory = new ClientPipelineFactory(executionHandler);        bootstrap.setPipelineFactory(clientPipelineFactory);        bootstrap.setOption("tcpNoDelay" ,true);          bootstrap.setOption("keepAlive", true);          bootstrap.connect(new InetSocketAddress(port));

 

Java Netty (1)