java nio oio_Netty NIO transport OIO transport
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 newsockets (server-side) and then creates a new thread for each accepted connection to serve thetraffic over the socket. This is needed asevery I/O operation on the socket may block at anytime.If you share the same thread over more than one connection (socket),this could lead toa 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 stillproviding the same way of building APIs. Here Netty makes use of theSO_TIMEOUTthat youcan set on a socket.This timeout specifies the maximum number of milliseconds to wait for anI/O operation to complete.If the operation doesn t complete within the specified timeout, aSocketTimeoutException is thrown.Netty catches this SocketTimeoutException andmoves on with its work. Then on the next EventLooprun, it tries again. Unfortunately, this isthe only way to do this and still confirm the inner working of Netty. The problem with thisapproach(途径) is that firing the SocketTimeoutException isn t free, as it needs to fill theStrackTrace, 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() {
@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
OP_ACCEPT
Get notified once a new connection is accepted and a channel is created.
OP_CONNECT
Get notified once a connection attempt finishes.
OP_READ
Get notified once data is ready to be read out of the channel.
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() {
@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=======
java nio oio_Netty NIO transport OIO transport相关推荐
- NIO详解(十三):Java IO 和NIO 总结
1. 概述 下面总结了Java NIO和IO之间的主要差别 IO NIO 面向流 面向缓冲 阻塞IO 非阻塞IO 无 选择器 2. Java IO和 NIO的主要区别 2.1 面向流和面向缓冲区 Ja ...
- Five ways to maximize Java NIO and NIO.2--转
原文地址:http://www.javaworld.com/article/2078654/java-se/java-se-five-ways-to-maximize-java-nio-and-nio ...
- 【学习笔记】JAVA IO与NIO(new IO)的对比与不同IO模型的理解
JAVA IO 分类: 几种IO 模型 1. 阻塞 IO 模型 2. 非阻塞 IO 模型 JAVA NIO 多路复用 IO 模型(即Java中的NIO) JAVA IO 思维导图: 分类: 按照流的方 ...
- Java NIO、NIO.2学习笔记
http://www.cnblogs.com/littlehann/p/3720396.html 相关学习资料 http://www.molotang.com/articles/903.html ...
- Java IO(BIO, NIO, AIO) 总结
文章转载自:JavaGuide 目录 BIO,NIO,AIO 总结 同步与异步 阻塞和非阻塞 1. BIO (Blocking I/O) 1.1 传统 BIO 1.2 伪异步 IO 1.3 代码示例 ...
- java中io.nio.aio_Java中网络IO的实现方式-BIO、NIO、AIO
在网络编程中,接触到最多的就是利用Socket进行网络通信开发.在Java中主要是以下三种实现方式BIO.NIO.AIO. 关于这三个概念的辨析以前一直都是好像懂,但是表达的不是很清楚,下面做个总结完 ...
- java 修改最大nio连接数_关于java流的几个概念:IO、BIO、NIO、AIO,有几个人全知道?...
关于同步.阻塞的知识我之前的文章有介绍,所以关于流用到这些概念与之前多线程用的概念一样. 下面具体来看看java中的几种流 IO/BIO BIO就是指IO,即传统的Blocking IO,即同步并阻塞 ...
- java 修改最大nio连接数_携程基于Quasar协程的NIO实践
IO密集型系统在高并发场景下,会有大量线程处于阻塞状态,性能低下,JAVA上成熟的非阻塞IO(NIO)技术可解决该问题.目前Java项目对接NIO的方式主要依靠回调,代码复杂度高,降低了代码可读性与可 ...
- java中的NIO和IO到底是什么区别?20个问题告诉你答案
摘要:NIO即New IO,这个库是在JDK1.4中才引入的.NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多. 本文分享自华为云社区<jav ...
最新文章
- Atitit.数据索引 的种类以及原理实现机制 索引常用的存储结构
- python线程同步锁_Python实现的多线程同步与互斥锁功能示例
- VTK:PolyData之ResamplePolyLine
- 重装机兵java_重装机兵之机甲咆哮
- WIN8将IE设置为默认浏览器
- 【转】Wireshark网络抓包(一)——数据包、着色规则和提示
- make 怎么降级_Ubuntu 中将 make 的版本降低
- Android配置http请求
- 计算机考试盘安装空间,2021上半年计算机水平考试模拟盘 安装
- 如何用python做软件导出cad_基于Python运用PyComCAD进行Autocad二次开发实例汇集
- openvswitch console输出
- 键入一个字母,如果小写字母输出大写,大写字母输出小写字母
- HTML文本格式化标签(用来调整文本的格式和排版)
- 水壶的问题—字节跳动Android岗面试题
- STM32工具使用---STM32CubeProgrammer更新固件
- 学会这招,远离年金险99%的坑
- GIS经纬度坐标转换为unity3D的世界坐标
- 最近在做的用户留存分析,和几种方法。
- 地方出现新一轮救市 北广深或跟进释放住房需求
- 联想 thindBook 13s G2 ITL笔记本开不了机问题
热门文章
- window10虚拟机下载地址
- vue 井号_使用Vue 2制作井字游戏:第1部分
- pandas之链式索引问题(chained indexing)
- [VMware]9破解版
- 2022第三届云原生编程挑战赛--Serverless VSCode WebIDE使用体验
- 四川职业技术学院linux,2019年四川交通职业技术学院单招中职(信息技术一类)专业技能测试大纲...
- Java-JFrame窗体美化
- python做地图热力图保存为png_Python如何实现热力图?可视化入库图实战演示
- 【Datawhale组队学习】机器学习数学基础 - 一元函数微分学的几何应用【Task 04】
- python去除图片马赛克_python 检测图片是否有马赛克