文档章节

Netty NIO transport && OIO transport

秋风醉了
 秋风醉了
发布于 2014/06/20 02:33
字数 1103
阅读 1405
收藏 2

Netty NIO transport && OIO transport


OIO  transport

The  OIO  transport  is  a  compromise(妥协)  in  Netty.  It  builds  on  the  known  unified(统一)  API  but isn t asynchronous(异步) by nature because it uses the blocking java.net implementations under the hood. At  first  glance, this  transport  may  not  look  useful  to  you,  but  it  has  its  use  cases. 

Because the OIO transport uses the java.net classes internally(内部的), it also uses the same logic that you may already be familiar with if you previously written network applications. When using these classes, you usually have one thread that handles the acceptance of new sockets (server-side) and then creates a new thread for each accepted connection to serve the traffic  over  the  socket.  This  is  needed  as  every  I/O  operation  on  the  socket  may  block  at  any time. If you share the same thread over more than one connection (socket), this could lead to a situation where blocking an operation could block all other sockets from doing their work. Knowing  that  operations  may  block,  you  may  start  to  wonder  how  Netty  uses  it  while  still providing  the  same  way  of  building  APIs.  Here Netty  makes  use  of  the SO_TIMEOUT that  you can set on a socket. This timeout specifies the maximum number of milliseconds to wait for an I/O operation  to  complete.  If  the  operation  doesn t  complete  within  the  specified  timeout,  a SocketTimeoutException is  thrown.  Netty  catches  this SocketTimeoutException and moves on with its work. Then on the next EventLooprun, it tries again. Unfortunately, this is the  only  way  to  do  this  and  still confirm the  inner  working  of  Netty.  The  problem  with  this approach(途径)  is  that  firing  the SocketTimeoutException isn t  free,  as  it  needs  to  fill  the StrackTrace, and so on. 

Netty OIO 编程模型

package nio2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Start  by  writing  a  blocking  version  of  the  application,
 * but  this  time  use  Netty  as  a  network
 * framework, as shown in the following listing.
 * 这是netty的阻塞IO的写法,同时也是同步的
 */
public class NettyOioServer {

    public void server(int port) throws Exception {
        final ByteBuf buf = Unpooled.wrappedBuffer(
                Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));

        // Use OioEventLoopGroup Ito allow blocking mode (Old-IO)
        EventLoopGroup group = new OioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(OioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                            //Specify ChannelInitializer that will be called for each accepted connection
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //Add ChannelHandler to intercept events and allow to react on them
                                    new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                            System.out.println("--active--");
                                            //Write message to client and add ChannelFutureListener to close connection once message written
                                            ctx.write(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                                        }
                                    });
                        }
                    });

            /**
             * Bind server to accept connections
             */
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }


    public static void main(String args[]) throws Exception {

        int port = 9898;
        NettyOioServer server = new NettyOioServer();
        System.out.println("bind port " + port);
        server.server(port);
    }
}


NIO  transport

selector-based

The  NIO  transport  is  currently  the  most  used.  It  provides  a  full  asynchronous  implementation of all I/O operations by using the selector-based approach that s included in Java since Java 1.4 and the NIO subsystem. 

The  idea  is  that  a  user  can  register  to  get  notified  once  a  channel s  state  changes. 

Selection operation bit-set

  1. OP_ACCEPT 

    Get notified once a new connection is accepted and a channel is created. 

  2. OP_CONNECT 

    Get notified once a connection attempt finishes. 

  3. OP_READ 

    Get notified once data is ready to be read out of the channel. 

  4. OP_WRITE 

    Get notified once it s possible to write more data to the channel. Most of the time this is possible, but it may not be because the OS socket buffer is completely filled. This usually happens when you write faster then the remote peer can handle it. 

Netty s NIO transport uses this model internally to receive and send data, but exposes its own API to the user, which completely hides the internal implementation. As mentioned previously, that  helps  to  expose  only  one  unified(统一的)  API  to  the  user,  while  hiding  all  of  the  internals(内部).

One feature that offers only the NIO transport at the moment is called zero-file-copy . This feature allows you to quickly and efficiently transfer content from your file system. The feature provides a way to transfer the bytes from the file system to the network stack without copying the bytes from the kernel space(内核态) to the user space(用户态)

Netty NIO 异步非阻塞编程模型

package nio2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Asynchronous networking with Netty
 * For now, I'll note that you can use ChannelHandlerfor these tasks:
 *  Transforming data from one format to another.
 *  Notifying you of exceptions.
 *  Notifying you when a Channel becomes active or inactive.
 *  Notifying you once a channel is registered/deregistered from an EventLoop.
 *  Notifying you about user-specific events.
 */
public class NettyNioServer {

    public void server(int port) throws Exception {
        final ByteBuf buf = Unpooled.wrappedBuffer(
                Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                            System.out.println("--active--");
                                            //Write message to client and add ChannelFutureListener to close connection once message written
                                            ctx.write(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                                        }
                                    });
                        }
                    });

            /**
             * Bind server to accept connections
             */
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }


    public static void main(String args[]) throws Exception {

        int port = 9898;
        NettyOioServer server = new NettyOioServer();
        System.out.println("bind port " + port);
        server.server(port);
    }
}

附:Netty提供的传输方式包括:

  • OIO

  • NIO

  • Local

  • Embedded

四种,以上只讲了两种。


写在后边

虽然通篇都是英文,但读起来感觉还是不错的,不常见的英文单词标注了中文。

通过最近一段时间的读英文文档,发现读起来不是很费劲了,至少感觉比读中文文档少了很多歧义。

自然有了google翻译的帮助,不会的单词都是小case,呵呵

=======END=======

© 著作权归作者所有

共有 人打赏支持
秋风醉了
粉丝 241
博文 566
码字总数 417505
作品 0
朝阳
程序员
私信 提问
第四章:Transports(传输)

本章内容 Transports(传输) NIO(non-blocking IO,New IO), OIO(Old IO,blocking IO), Local(本地), Embedded(嵌入式) Use-case(用例) APIs(接口) 网络应用程序都是以字节码传输。Java开发网络...

李矮矮
2016/09/23
16
0
Java NIO && Netty的epoll实现

Java NIO && Netty的epoll实现 Java NIO Java NIO根据操作系统不同, 针对nio中的Selector有不同的实现: macosx: KQueueSelectorProvider solaris: DevPollSelectorProvider Linux: EPollSe......

秋风醉了
2016/03/18
324
0
Epoll_native non-blocking transport for Linux

Epoll_native non-blocking transport for Linux As we explained earlier, Netty’s NIO transport is based on the common abstraction for asynchronous/non-blocking networking provide......

秋风醉了
2016/03/24
23
0
Netty 4.0.0.CR6 发布,高性能网络服务框架

Netty 4.0 发布第 6 个 RC 版本,该版本值得关注的改进有: and now works correctly. (#1475 and #1471) Android compatibility issues has been fixes. (#1451 and #1472) now works corr......

oschina
2013/06/21
2.6K
13
Netty 3.6.4.Final 发布

Netty 提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。 体系结构图 Netty 发布 3.6.4 更新版本,主要改进包括: You can specify ...

oschina
2013/04/05
1K
1

没有更多内容

加载失败,请刷新页面

加载更多

CSS 选择器参考手册

CSS 选择器参考手册 选择器 描述 [attribute] 用于选取带有指定属性的元素。 [attribute=value] 用于选取带有指定属性和值的元素。 [attribute~=value] 用于选取属性值中包含指定词汇的元素。...

Jack088
27分钟前
0
0
数据库篇一

数据库篇 第1章 数据库介绍 1.1 数据库概述  什么是数据库(DB:DataBase) 数据库就是存储数据的仓库,其本质是一个文件系统,数据按照特定的格式将数据存储起来,用户可以对数据库中的数据...

stars永恒
37分钟前
2
0
Intellij IDEA中设置了jsp页面,但是在访问页面时却提示404

在Intellij IDEA中设置了spring boot的jsp页面,但是在访问时,却出现404,Not Found,经过查找资料后解决,步骤如下: 在Run/Debug Configurations面板中设置该程序的Working Directory选项...

uknow8692
昨天
2
0
day24:文档第五行增内容|每月1号压缩/etc/目录|过滤文本重复次数多的10个单词|人员分组|

1、在文本文档1.txt里第五行下面增加如下内容;两个方法; # This is a test file.# Test insert line into this file. 分析:给文档后增加内容,可以用sed 来搞定;也可以用while do done...

芬野de博客
昨天
2
0
深入理解JVM—JVM内存模型

深入理解JVM—JVM内存模型 我们知道,计算机CPU和内存的交互是最频繁的,内存是我们的高速缓存区,用户磁盘和CPU的交互,而CPU运转速度越来越快,磁盘远远跟不上CPU的读写速度,才设计了内存...

onedotdot
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部