1.FileChannel
package io.pdd.nio.file;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class RdmAccFile {
public static void main(String[] args) throws Exception {
//读取文件
RandomAccessFile randomAccessFile=new RandomAccessFile("E:/random.txt","rw");
//获取Channel
FileChannel fileChannel=randomAccessFile.getChannel();
//创建ByteBuffer
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
//从通道读取数据到byteBuffer
int read = fileChannel.read(byteBuffer);
while(read!=-1){
//将position回归到起始位置 limit设置为position的位置(为什么这么用请看上一篇理论知识)
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
System.out.print((char)byteBuffer.get());
}
//清空已经读取过的数据(position之前的)
byteBuffer.compact();
read=fileChannel.read(byteBuffer);
}
}
}
2.ScoketChannel、ServerSocketChannel
服务端
package io.pdd.nio.data;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
/**
* @author:liyangpeng
* @date:2020/5/20 13:45
*/
public class NioServer {
/**
*
* @param key
* @throws IOException
*/
public static void handleAccept(SelectionKey key) throws IOException{
ServerSocketChannel ssChannel = (ServerSocketChannel)key.channel();
SocketChannel sc = ssChannel.accept();
sc.configureBlocking(false);
sc.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocateDirect(1024));
}
/**
* 数据读取
* @param key
* @throws IOException
*/
public static void handleRead(SelectionKey key) throws IOException{
SocketChannel sc = (SocketChannel)key.channel();
sc.configureBlocking(false);
ByteBuffer buf = (ByteBuffer)key.attachment();
Charset c = Charset.forName("UTF-8");
CharsetDecoder decoder = c.newDecoder();
int bytesRead = sc.read(buf);
while(bytesRead>0){
buf.flip();
CharBuffer cb = CharBuffer.allocate(bytesRead);
decoder.decode(buf, cb, false);
cb.flip();
while(cb.hasRemaining()){
System.out.print(cb.get());
}
System.out.println();
cb.clear();
buf.clear();
bytesRead = sc.read(buf);
}
if(bytesRead == -1){
sc.close();
}
}
/**
*
* @param key
* @throws IOException
*/
public static void handleWrite(SelectionKey key) throws IOException{
ByteBuffer buf = (ByteBuffer)key.attachment();
buf.flip();
SocketChannel sc = (SocketChannel) key.channel();
while(buf.hasRemaining()){
sc.write(buf);
}
buf.compact();
}
/**
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Selector selector=Selector.open();
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8899));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while(true){
if(selector.select(3000)==0){
System.out.println("continue...");
continue;
}
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey next = iterator.next();
if(next.isAcceptable()){
handleAccept(next);
System.out.println("accept...");
}
if(next.isReadable()){
handleRead(next);
System.out.println("read..");
}
// if(next.isWritable()){
// handleWrite(next);
// System.out.println("write...");
// }
// if(next.isConnectable()){
// System.out.println("connect...");
// }
iterator.remove();
}
}
}
}
客户端
package io.pdd.nio.data;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
* @author:liyangpeng
* @date:2020/5/25 14:02
*/
public class NioClient {
public static void main(String[] args) {
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
SocketChannel socketChannel=null;
try{
socketChannel=SocketChannel.open();
socketChannel.connect(new InetSocketAddress(8899));
socketChannel.configureBlocking(false);
if(socketChannel.finishConnect()){
String info="我是新来的client...";
byteBuffer.put(info.getBytes("UTF-8"));
byteBuffer.flip();
socketChannel.write(byteBuffer);
}
byteBuffer.clear();
socketChannel.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
3.Pipe
package io.pdd.nio.data;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author:liyangpeng
* @date:2020/5/25 14:52
*/
public class PipeTest {
private final static String CHARSET="UTF-8";
public static void main(String[] args) throws IOException {
//线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
Pipe pipe=Pipe.open();
//线程写
executorService.submit(()->{
Pipe.SinkChannel sinkChannel=pipe.sink();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
while(true){
String timestamp=System.currentTimeMillis()+"";
byteBuffer.put(timestamp.getBytes(CHARSET));
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
sinkChannel.write(byteBuffer);
}
byteBuffer.clear();
}
});
//线程读
executorService.submit(()->{
Pipe.SourceChannel sinkChannel=pipe.source();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
while(true){
int length=sinkChannel.read(byteBuffer);
while(length>0){
byteBuffer.flip();
byte [] bt=new byte[length];
int index=0;
while(byteBuffer.hasRemaining()){
bt[index]=byteBuffer.get();
index++;
}
System.out.println(new String(bt,CHARSET));
byteBuffer.clear();
bt=null;
length=sinkChannel.read(byteBuffer);
}
}
});
}
}
4.DatagramChannel
接收端
package io.pdd.nio.udp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
/**
* @author:liyangpeng
* @date:2020/5/25 15:13
*/
public class DatagramReviceTest {
public static void main(String[] args) throws IOException {
DatagramChannel channel=DatagramChannel.open();
// channel.configureBlocking(false);使用非堵塞
channel.socket().bind(new InetSocketAddress("127.0.0.1",8901));
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
byteBuffer.clear();
channel.receive(byteBuffer);
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
System.out.print((char)byteBuffer.get());
}
System.out.println();
byteBuffer.clear();
channel.close();
}
}
发送端
package io.pdd.nio.udp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
/**
* @author:liyangpeng
* @date:2020/5/25 15:14
*/
public class DatagramSendChannel {
public static void main(String[] args) throws IOException {
DatagramChannel datagramChannel= DatagramChannel.open();
String text="hello word!";
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
byteBuffer.put(text.getBytes("UTF-8"));
byteBuffer.flip();
int send = datagramChannel.send(byteBuffer, new InetSocketAddress("127.0.0.1",8901));
System.out.println(send);
byteBuffer.clear();
datagramChannel.close();
}
}