java nio之channel
一、通道(Channel):由 java.nio.channels 包定义的。Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据,Channel 只能与Buffer 进行交互。
二、Channel重要实现
- FileChannel:操作文件的读写
- SocketChannel:通过TCP读写网络数据
- ServerSocketChannel:监听TCP连接,你能利用它创建一个最简单的Web服务器
- DatagramChannel:通过UDP读写网络数据
三、FileChannel 的文件读写
1)利用FileChannel 本身提供的transferTo进行数据的读写。
package com.troy.nio.application; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel; public class Channel { public static void main(String[] args) throws Exception {
//读取文件
FileInputStream fileInputStream = new FileInputStream("d:/t.txt");
//写出文件
FileOutputStream fileOutputStream = new FileOutputStream("d:/e.txt");
//获取读取通道
FileChannel inChannel = fileInputStream.getChannel();
//获取写入通道
FileChannel outChannel = fileOutputStream.getChannel();
//完成数据的写入
inChannel.transferTo(,inChannel.size(),outChannel);
}
}
2)利用FileChannel 提供的读写方法
package com.troy.nio.application; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; public class Channel { public static void main(String[] args) throws Exception {
//读取文件
FileInputStream fileInputStream = new FileInputStream("d:/t.txt");
//写出文件
FileOutputStream fileOutputStream = new FileOutputStream("d:/e.txt");
//获取读取通道
FileChannel inChannel = fileInputStream.getChannel();
//获取写入通道
FileChannel outChannel = fileOutputStream.getChannel();
//缓存
ByteBuffer byteBuffer = ByteBuffer.allocate();
//读取数据
while (inChannel.read(byteBuffer) != -) {
//转换成可读写
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(),"GBK").trim());
//写出数据,清楚缓存
outChannel.write(byteBuffer);
byteBuffer.clear();
}
}
}
四、SocketChannel和ServerSocketChannel在同时使用时,都是tcp协议进行传输的,在使用上面比较服务具体的协议控制
具体的应用可以参考:http://www.cnblogs.com/ll409546297/p/7929646.html
五、DatagramChannel的方式
1)客户端
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel; public class UDPClient { public static void main(String[] args) throws Exception { //获取UDP通道
DatagramChannel datagramChannel = DatagramChannel.open();
//设置非阻塞
datagramChannel.configureBlocking(false);
//发送数据
datagramChannel.send(ByteBuffer.wrap("hello server!".getBytes()),new InetSocketAddress("localhost",));
}
}
2)服务端的2中写法,阻塞和非阻塞
1、阻塞
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel; public class UDPServer { //UDP通道
private static DatagramChannel datagramChannel; public static void main(String[] args) throws Exception {
serverInit();
listen();
} //初始化
private static void serverInit() throws IOException {
//获取UDP通道
datagramChannel = DatagramChannel.open();
//设置接收端口
datagramChannel.socket().bind(new InetSocketAddress());
} //监听
private static void listen() throws IOException {
while (true) {
//接收的长度
ByteBuffer byteBuffer = ByteBuffer.allocate();
//这里会阻塞
datagramChannel.receive(byteBuffer);
byteBuffer.flip();
System.out.println(new String(byteBuffer.array()).trim());
}
}
}
2、非阻塞,利用selector来进行数据选择
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator; public class UDPServer { //选择器
private static Selector selector;
//UDP通道
private static DatagramChannel datagramChannel; public static void main(String[] args) throws Exception {
serverInit();
listen();
} //初始化
private static void serverInit() throws IOException {
//获取选择器
selector = Selector.open();
//获取UDP通道
datagramChannel = DatagramChannel.open();
//设置非阻塞
datagramChannel.configureBlocking(false);
//设置接收端口
datagramChannel.socket().bind(new InetSocketAddress());
//注册
datagramChannel.register(selector, SelectionKey.OP_READ);
} //监听
private static void listen() throws IOException {
while (true) {
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
if (selectionKey.isReadable()) {
//接收的长度
ByteBuffer byteBuffer = ByteBuffer.allocate();
//这里不会阻塞
datagramChannel.receive(byteBuffer);
byteBuffer.flip();
System.out.println(new String(byteBuffer.array()).trim());
}
}
}
}
}
六、基本上channel的实现用法就这些了,但是里面会涉及到很多细节的用法,这个需要自己进一步研究
java nio之channel的更多相关文章
- Java NIO -- 通道 Channel
通道(Channel):由 java.nio.channels 包定义的.Channel 表示 IO 源与目标打开的连接.Channel 类似于传统的“流”.只不过 Channel本身不能直接访问数据 ...
- Java NIO 之 Channel(通道)
历史回顾: Java NIO 概览 Java NIO 之 Buffer(缓冲区) 其他高赞文章: 面试中关于Redis的问题看这篇就够了 一文轻松搞懂redis集群原理及搭建与使用 一 Channel ...
- 【Java nio】Channel
package com.slp.nio; import org.junit.Test; import java.io.*; import java.nio.ByteBuffer; import jav ...
- JAVA NIO 之Channel
缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存.Channel 通道就是将数据传输给 ByteBuffer 对象或者从 ByteBuffer 对象获取数据进行传输. Channel 用于在 ...
- Java NIO教程 Channel
Channel是一个连接到数据源的通道.程序不能直接用Channel中的数据,必须让Channel与BtyeBuffer交互数据,才能使用Buffer中的数据. 我们用FileChannel作为引子, ...
- 《JAVA NIO》Channel
3.通道 Channle主要分为两类:File操作对应的FIleChannel和Stream操作对应的socket的3个channe. 1.这3个channel都是抽象类.其具体实现在SPI里面. 2 ...
- (转)[疯狂Java]NIO:Channel的map映射
原文出自:http://blog.csdn.net/lirx_tech/article/details/51396268 1. 通道映射技术: 1) 其实就是一种快速读写技术,它将通道所连接的数据节点 ...
- 关于java nio的channel读写的一个困惑
这里提的需求基本都是IM的,IM的解决方案是怎么样的? 网上的需求: 1. 某一用户发了一条信息, 需要服务器反回一个信息(这种最简单) 2. 某一用户发了一条信息,需要服务器广播给所有客户端 3. ...
- JAVA NIO Selector Channel
These four events are represented by the four SelectionKey constants: SelectionKey.OP_CONNECT Select ...
随机推荐
- Android进阶笔记17:Android手机屏幕坐标系
1. 手机屏幕坐标系: 整个坐标系是以手机屏幕左上角为原点(0,0),如下:
- Mybatis批量插入及传参问题
先看需求:将报文对象Message批量插入分库分表的Oracle数据库中 一般如果直接传入List的话,需要加上parameterType="java.util.List" ,然后 ...
- 【[AHOI2005]航线规划】
树剖维护边双 首先我们看到在整个过程中图是保证连通的,于是我们并不需要LCT来维护连通性 而这些询问询问的是两个点之间关键路径的数量,也就是无论怎么走都必须走的数量,显然这就是两点之间的割边的数量 由 ...
- thinkphp清除缓存
前台 //清除缓存 $(function(){ $("#cache").click(function(){ layer.confirm('你确定要清除缓存吗?', {icon: 3 ...
- Spring(十九)之异常处理
异常处理,对于项目开发至关重要,总不能用户点击一个页面出错了,直接报500,那样用户体验多不好啊! 所以这里讲的是SpringMVC对异常的处理,希望能给大家带来一定的 帮助和启发. 一.编写实体 p ...
- 为GRIDVIEW“删除”列添加确认对话框
如何为gridview控件里的“删除”列添加一个确认对话框?网上众说纷纭,大致见到了三种解决方案,现归纳如下:1.继承Web.IO里的button控件,为其实现一个IPostback的接口用于回调,具 ...
- 锐捷交换机RG-3760-24 的简单配置与VLAN搭建
要做的事 将交换机和主机连通. 建立vlan,并将主机配置到vlan当中. 连接主机和交换机 安装配置软件 选用SecureCRT 8.0来配置交换机,可在网上下载. 插入配置线 把配置线插入cons ...
- Visual Studio 中常用的快捷键
项目相关的快捷键 Ctrl + Shift + B = 生成项目 Ctrl + Alt + L = 显示 Solution Explorer(解决方案资源管理器) Shift + Alt+ C = 添 ...
- 爬虫之Beautifulsoup及xpath
1.BeautifulSoup (以 Python 风格的方式来对 HTML 或 XML 进行迭代,搜索和修改) 1.1 介绍 Beautiful Soup提供一些简单的.python式的函数用来处理 ...
- windows安装的mysql中文乱码的坑
本机装的mysql为5.6的,从代码执行的中文inert语句总是显示问号,然后在中文查询是都会报问题 今天终于解决了! 问题解决方法为: 找到my.ini文件在文件中加入 [client]defaul ...