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 ...
随机推荐
- springmvc常用注解标签详解(转载)
1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ...
- SOJ4478 Easy Problem II(模拟、栈)
Time Limit: 3000 MS Memory Limit: 131072 K Description 在数据结构中 我们学习过 栈 这种数据结构 通过栈 我们可以将1,2,3,...,n转化成 ...
- 【[ZJOI2005]午餐】
首先我们得贪心一下,让吃饭时间较长的人排在队首 去抄一段贪心的证明吧 现在研究在一个队伍里的人有什么性质 可以发现道题里也有一个不变量,就是对于队伍里的前\(i\)个人,不管他们排队的顺序如何,\(a ...
- HDU 1281 棋盘游戏 【二分图最大匹配】
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1281 题意概括: 有N*M大的棋盘,要在里面放尽量多的“车”,求最多能放的车的个数,和为了放最多的车有多 ...
- 关于Git学习推荐
Git学习除了推荐官方网站:https://git-scm.com/之外, 我个人比较推荐初学者或者被动使用者可以学习参考廖雪峰的这个教程:https://www.liaoxuefeng.com/wi ...
- iOS开发之GCD总结
直接贴出常用的函数,方便要用的时候直接使用. ------------- type 1 ---------------- 说明 : 创建一个dispatch_group_t,每次网络请求前先 ...
- heatmap for arcgisjsapi
在arcgis for js api 环境下使用heatmap插件. 由于最新的heatmap没有提供 for arcgisjsapi 插件,懒得研究新版本代码,所以这里用的还是老版本的heatma ...
- Git如何从github上pull别人的项目
1:使用git方式导入项目 菜单-File->import->Git->Projects from Git 2:选择某个服务器上的资源 3:选择需要pull的地址 后面需要自己加上 ...
- OSMboxPend()
1. 原型:void *OSMboxPend(OS_EVENT *pevent, INT16U timeout, INT8U *err) 2. 参数意义: pevent :消息邮箱 timeout ...
- Java并发包:AtomicBoolean和AtomicReference
AtomicBoolean AtomicBoolean是一个读和写都是原子性的boolean类型的变量.这里包含高级的原子操作,例如compareAndSet().AtomicBoolean位于J ...