文章目录
- 学习netty之前先学习NIO基础
- NIO基础
- 1.三大组件(Channel,Buffer,Selector)
- 2. ByteBuffer
- 3.文件编程
- 4.网络编程
- 网络编程小结:
- 非阻塞 VS 阻塞
- 1.1 阻塞
- 1.2 非阻塞
- 1.3 多路复用
- selector何时不阻塞
- 监听channel事件
- 更进一步优化
- 5. NIO vs BIO
- 5.1 stream VS channel
- 5.2 IO模型(下面的几个IO概念可能不清晰,有个大概,如果要详细看可以百度认真了解IO概念)
- 5.3零拷贝(针对java里面不用拷贝)
- 传统IO问题
- NIO优化
- 进一步优化
- 进一步优化(linux2.4)
- 5.4 AIO
学习netty之前先学习NIO基础
NIO基础
1.三大组件(Channel,Buffer,Selector)
- 1.1 Channel (读写双向管道)和 Buffer(可以将Channel的数据读入Buffer,也可将buffer的数据写入channel)
- 常见的Channel有
- 1.FileChannel (使用)
- 2.DatagramChannel (使用UDP网络时候)
- 3.SocketChannel (使用TCP的时候,服务器和客户端都可以用)
- 4.ServerSocketChannel (使用TCP的时候,专用于服务器的时候)
- 常见的Buffer缓冲区
- ByteBuffer(常用)
- MappedByteBuffer
- DirectByteBuffer
- HeapByteBuffer
- ShortBuffer
- IntBuffer
- LongBuffer
- FloatBuffer
- DoubleBuffer
- CharBuffer
- 1.2 Selector
- 多线程版本设计,一个客户端一个socket线程,多了的话,可能造成内存溢出。缺点内存占用高;线程上下文切换成本高;只适合连接数少的场景。
- 线程池版本的设计,缺点:阻塞模式下,线程仅能处理一个socket连接;仅适合短链接的场景。(适合http请求)
- Selector版本的设计。selector的作用就是配合一个线程来管理多个channel,获取这些channel上发生的事件,这些channel工作在非阻塞模式下,不会让线程吊死在一个channel上,适合连接数多,流量低的场景(low traffic);调用selector的select()方法会阻塞直到发生了读写就绪事件,一旦这些事件发生,selector方法就会返回这些事件交给thread处理。
2. ByteBuffer
package com.dapeng.netty;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@Slf4j
public class TestByteBuffer {
public static void main(String[] args) {
try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(10);
while (true){
int len = channel.read(buffer);
log.debug("读取到的字节数为:{}",len);
if (len == -1){
break;
}
buffer.flip();
while (buffer.hasRemaining()){
byte b = buffer.get();
log.debug("读取到的实际字节:{}",(char)b);
}
buffer.clear();
}
} catch (IOException e) {
}
}
}
- 2.ByteBuffer正确使用姿势
- 2.1向buffer写入数据的时候,例如调用channel.read(buffer)。
- 2.2 调用buffer.filp(); 切换为读模式
- 2.3 从buffer读取数据,例如调用buffer.get();获取单个字节
- 2.4 调用buffer.clear(),或者compact() 切换至 写模式
- 2.5 重复1-4步骤。
- 3.ByteBuffer结构
- 3.1ByteBuffer有一下几个重要属性:
- Capacity(容量)
- Position(当前位置)
- LImit(写入限制)
如下图所示:
- 3.2 读写切换
- 1.刚开始为写模式:
- 2 切换读的时候,调用filp()
- 3.读取完后,如图:
-
- 切换回来为写模式,调用clear()方法。
- 5.特殊的compact的方法,在读取一部分或者因为默写情况未读完,则需要在未读的数据后面追加写入。从未读完的那里开始,重新写入。
读写实例:
(以下所有代码需要用到该类)首先拿到工具类:
package com.dapeng.netty.utils;
import java.nio.ByteBuffer;
import static io.netty.util.internal.StringUtil.NEWLINE;
import static io.netty.util.internal.MathUtil.isOutOfBounds;
import io.netty.util.internal.StringUtil;
public class ByteBufferUtil {
private static final char[] BYTE2CHAR = new char[256];
private static final char[] HEXDUMP_TABLE = new char[256 * 4];
private static final String[] HEXPADDING = new String[16];
private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
private static final String[] BYTE2HEX = new String[256];
private static final String[] BYTEPADDING = new String[16];
static {
final char[] DIGITS = "0123456789abcdef".toCharArray();
for (int i = 0; i < 256; i++) {
HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
}
int i;
for (i = 0; i < HEXPADDING.length; i++) {
int padding = HEXPADDING.length - i;
StringBuilder buf = new StringBuilder(padding * 3);
for (int j = 0; j < padding; j++) {
buf.append(" ");
}
HEXPADDING[i] = buf.toString();
}
for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
StringBuilder buf = new StringBuilder(12);
buf.append(NEWLINE);
buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
buf.setCharAt(buf.length() - 9, '|');
buf.append('|');
HEXDUMP_ROWPREFIXES[i] = buf.toString();
}
for (i = 0; i < BYTE2HEX.length; i++) {
BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
}
for (i = 0; i < BYTEPADDING.length; i++) {
int padding = BYTEPADDING.length - i;
StringBuilder buf = new StringBuilder(padding);
for (int j = 0; j < padding; j++) {
buf.append(' ');
}
BYTEPADDING[i] = buf.toString();
}
for (i = 0; i < BYTE2CHAR.length; i++) {
if (i <= 0x1f || i >= 0x7f) {
BYTE2CHAR[i] = '.';
} else {
BYTE2CHAR[i] = (char) i;
}
}
}
public static void debugAll(ByteBuffer buffer) {
int oldlimit = buffer.limit();
buffer.limit(buffer.capacity());
StringBuilder origin = new StringBuilder(256);
appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
System.out.println("+--------+-------------------- all ------------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
System.out.println(origin);
buffer.limit(oldlimit);
}
public static void debugRead(ByteBuffer buffer) {
StringBuilder builder = new StringBuilder(256);
appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
System.out.println("+--------+-------------------- read -----------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
System.out.println(builder);
}
private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
if (isOutOfBounds(offset, length, buf.capacity())) {
throw new IndexOutOfBoundsException(
"expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
+ ") <= " + "buf.capacity(" + buf.capacity() + ')');
}
if (length == 0) {
return;
}
dump.append(
" +-------------------------------------------------+" +
NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
NEWLINE + "+--------+-------------------------------------------------+----------------+");
final int startIndex = offset;
final int fullRows = length >>> 4;
final int remainder = length & 0xF;
for (int row = 0; row < fullRows; row++) {
int rowStartIndex = (row << 4) + startIndex;
appendHexDumpRowPrefix(dump, row, rowStartIndex);
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(" |");
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append('|');
}
if (remainder != 0) {
int rowStartIndex = (fullRows << 4) + startIndex;
appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(HEXPADDING[remainder]);
dump.append(" |");
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append(BYTEPADDING[remainder]);
dump.append('|');
}
dump.append(NEWLINE +
"+--------+-------------------------------------------------+----------------+");
}
private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
if (row < HEXDUMP_ROWPREFIXES.length) {
dump.append(HEXDUMP_ROWPREFIXES[row]);
} else {
dump.append(NEWLINE);
dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
dump.setCharAt(dump.length() - 9, '|');
dump.append('|');
}
}
public static short getUnsignedByte(ByteBuffer buffer, int index) {
return (short) (buffer.get(index) & 0xFF);
}
}
package com.dapeng.netty;
import java.nio.ByteBuffer;
import static com.dapeng.netty.utils.ByteBufferUtil.debugAll;
public class TestByteBufferReadWrite {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put((byte) 0x61);
debugAll(buffer);
buffer.put(new byte[]{ 0x62, 0x63, 0x64});
debugAll(buffer);
buffer.flip();
System.out.println("读模式" + buffer.get());
debugAll(buffer);
buffer.compact();
debugAll(buffer);
buffer.put(new byte[]{ 0x65, 0x6f});
debugAll(buffer);
}
}
package com.dapeng.netty;
import java.nio.ByteBuffer;
public class TestByteBufferAllocate {
public static void main(String[] args) {
System.out.println(ByteBuffer.allocate(16).getClass());
System.out.println(ByteBuffer.allocateDirect(16).getClass());
}
}
- 4.2 从buffer写入数据
- 调用channel的read方法。
- 调用buffer的put方法。
int readBytes = channel.read(buf)