ChannelPipeline中每个节点是一个Context,用Context包装Handler,由Context组成双向链表,节点间通过AbstractChannelHandlerContext 类内部的 fire 系列方法 进行传递,入站方法叫inbound,从head节点开始,出站方法叫outbound,由tail节点开始。
package com.atguigu.bio;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class BIOClient {
public static void main(String[] args) throws Exception {
Socket client = new Socket("127.0.0.1", 8080);
Scanner scan = new Scanner(System.in);
PrintStream out = new PrintStream(client.getOutputStream());
BufferedReader bufferReader =
new BufferedReader(new InputStreamReader(client.getInputStream()));
while (true) {
if (scan.hasNext()) {
// 键盘输入,并发送请求
String str = scan.next();
if ("exit".equalsIgnoreCase(str)) {
break;
}
out.println(str);
out.flush();
// 接收服务端的响应
System.out.println(bufferReader.readLine());
}
}
client.close();
}
}
// 下一个要读或写的位置索引
private int position = 0;
// 缓冲区的当前终点,<= limit,读写时位置索引不能超出limit
private int limit;
// 缓冲区容量
private int capacity;
// 标记,标记后用于重新恢复到的位置
private int mark = -1;
package com.nixum.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class CopyFileAToB {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("first.txt");
FileChannel readFileChannel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("second.txt");
FileChannel writeFileChannel = fileOutputStream.getChannel();
// 只设置成1024的容量,通过循环 + clear覆盖重写
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
byteBuffer.clear();
int read = readFileChannel.read(byteBuffer);
if (read == -1) {
break;
}
// 写操作前需要先flip
byteBuffer.flip();
writeFileChannel.write(byteBuffer);
}
// close
fileInputStream.close();
fileOutputStream.close();
}
}