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 ...
随机推荐
- codeforces793 B. Igor and his way to work (dfs)
题目链接:codeforces793 B. Igor and his way to work (dfs) 求从起点到终点转方向不超过两次是否有解,,好水啊,感觉自己代码好搓.. #include< ...
- FZU-1759 Super A^B mod C---欧拉降幂&指数循环节
题目链接: https://cn.vjudge.net/problem/FZU-1759 题目大意: 求A^B%C 解题思路: 注意,这里long long需要用%I64读入,不能用%lld #inc ...
- mysql 表名区分大小写
原来Linux下的MySQL默认是区分表名大小写的,通过如下设置,可以让MySQL不区分表名大小写:1.用root登录,修改 /etc/my.cnf:2.在[mysqld]节点下,加入一行: lowe ...
- libconfig C++ 学习笔记
1. C++API 头文件 #include <libconfig.h++> ,命名空间:using namespace libconfig; 2.多线程使用问题: (1)libconfi ...
- log4net快速使用流程
以下内容大部分来自这里,对原作者流子表示感谢 1.Nuget安装,当前版本2.0.8 2.创建log4net.config文件,文件内容如下: <?xml version="1.0&q ...
- 关于js点击事件出现 xx is not defined at HTMLAnchorElement.onclick 的问题
测试: html: <button onclick="abc();">点我点我!</button> js: function abc(){ alert(“1 ...
- [转]MFC子线程更改图像数据后更新主窗口图像显示方法
程序思路是由外部的输入输出控制卡发出采集图像信号,之后相机采集图像得到图像数据指针,接收图像数据指针创建成图像最后显示到MFC对话框应用程序的Picture Control控件上,同时,为了标定相机位 ...
- 对IIS7经典模式和集成模式的理解(转载)
从IIS6新增应用程序池的概念,到现在IIS7,对HTTP请求处理功能已经越来越精确化和不断改善,IIS7应用程序池新增了经典模式和集成模式可供选择,不管官方还是一些书籍或文章都有介绍,但多数过于官方 ...
- Unity 游戏框架搭建 2018 (二) 单例的模板与最佳实践
Unity 游戏框架搭建 2018 (二) 单例的模板与最佳实践 背景 很多开发者或者有经验的老手都会建议尽量不要用单例模式,这是有原因的. 单例模式是设计模式中最简单的也是大家通常最先接触的一种设计 ...
- 几行代码实现iOS摇一摇功能
实现这个功能很简单,我们直接看代码 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{ NSLog(@&quo ...