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 ...
随机推荐
- bzoj5152 [Wc2018]通道
题目链接 正解:不会做. 写一个爬山算法就过官方数据了(逃 具体来说就是每次随机一个根,然后迭代找最长路的那个点. 多随机几次取$max$就行了.正解以后再补.. #include <bits/ ...
- Django objects.values
values(*fields) 返回一个ValuesQuerySet —— QuerySet 的一个子类,迭代时返回字典而不是模型实例对象. 每个字典表示一个对象,键对应于模型对象的属性名称. 下面的 ...
- PHP 获取数组随意下标key的上一个prev和下一个next下标值
PHP 获取数组随意下标key的上一个prev和下一个next下标值 <? php $xoops[1] = '小'; $xoops[2] = '孩'; $xoops[3] = '子'; $xoo ...
- 十.mysqld_multi stop无效问题
今天在尝试运行mysqld_report stop的时候,发现无法停止mysql,日志中的错误如下 Stopping MySQL servers mysqladmin: [Warning] Using ...
- gluoncv 目标检测,训练自己的数据集
https://gluon-cv.mxnet.io/build/examples_datasets/detection_custom.html 官方提供两种方案,一种是lst文件,一种是xml文件(v ...
- PHP------析构方法
析 构 方 法 封装,有一个叫构造函数 和构造函数对应的还有一种方法叫做析构. class ren //一个类 是 人类 { public $mingzi ://成员变量 punction__d ...
- linq 和lamba表达式
一.什么是Linq(what)二.Linq的优点(why)三.Linq查询的步骤(how)四.查询基本操作五.結合實例代碼(具體聯繫用linqtosql來寫的增刪改查)一.什么是Linq(what). ...
- Lambda使用
说明 本文内容来自 [Java8 In Action] 一书 四种方法引用类型 类型 示例 引用静态方法 ContainingClass::staticMethodName 引用某个对象的实例方法 c ...
- HDU 2717 Catch That Cow(常规bfs)
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2717 Catch That Cow Time Limit: 5000/2000 MS (Java/Oth ...
- CSS技巧之向下箭头
思路:使用◇符号(可在输入法的软键盘找到该符号),使用定位选择位置,并隐藏溢出的上半部分细点:1.使用i标签的楷体属性把◇变大2.给i只有◇符号一半的高度,并隐藏溢出,正常显示一个向上箭头3.对s使用 ...