该栏目讲解NIO、Netty组件、Netty参数调优、粘包与半包解决方案、聊天室
文章目录
NIO 基础
1、NIO 简介
概述
:NIO,全称 non-blocking io,是非阻塞 IO三大组件
- Channel
- Buffer
- Selector
2、IO 模型
同步阻塞
:线程自己等待结果同步非阻塞
:线程自己非阻塞的获取结果多路复用
:线程使用 selector 去等待事件的触发异步非阻塞
:一个线程调用获取方法,另一个线程等待结果并返回
3、零拷贝
传统 IO 问题
:Java本身并不具备 IO 读写能力,因此要去调用操作系统的读写能力
NIO 优化
:通过 DirectByteBuffer 使用的是操作系统内存,来减少读写
Linux 优化
- java 调用 transferTo() 方法后,要从 java 程序的用户态切换至内核态,使用 DMA(Direct Memory Access)将数据读入内核缓冲区,不会使用 CPU
- 只会将一些 offset 和 length 信息拷入socket 缓冲区,几乎无消耗
- 使用 DMA 将内核缓冲区的数据写入网卡,不会使用 CPU
4、Channel 通道
概述
:Channel 是一个读写数据的双向通道常见 channel
- FileChannel:文件通道
- DatagramChannel:数据包通道,用于 UDP 协议
- SocketChannel:套接字通道,用于 TCP 协议
- ServerSocketChannel:套接字服务端通道,用于 TCP 协议
Stream 与 Channel
- Stream 不会自动缓冲数据,而 Channel 会利用系统提供的发送缓冲区、接收缓冲区
- Stream 仅支持阻塞 API,Channel 同时支持阻塞、非阻塞 API,网络 Channel 可配合 Selector 实现多路复用
- 二者均为全双工
5、Buffer 缓存区
概述
: Buffer 用于缓冲数据的缓存区,是非线程安全的常见 Buffer
- ByteBuffer
- MappedByteBuffer
- DirectByteBuffer
- HeapByteBuffer
- ShortBuffer
- IntBuffer
- LongBuffer
- FloatBuffer
- DoubleBuffer
- CharBuffer
- ByteBuffer
6、Selector 选择器
概述
: Selector 配合一个线程来管理多个 Channel,获取这些 Channel 上发生的事件,这些 Channel 工作在非阻塞模式下,不会让线程吊死在一个 Channel 上, 适合连接数特别多,但流量低的场景
ByteBuffer
1、ByteBuffer 结构
-
ByteBuffer 有以下重要属性
- capacity
- position
- limit
-
一开始
-
写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态
-
flip 动作发生后,position 切换为读取位置,limit 切换为读取限制
-
读取 4 个字节后,状态
-
clear 动作发生后,状态
-
compact 方法,是把未读完的部分向前压缩,然后切换至写模式
2、ByteBuffer 常用方法
2.1 分配空间
- :使用 allocate() 方法为 ByteBuffer 分配空间,其他 buffer 类也有该方法
ByteBuffer buf = ByteBuffer.allocate(16);
2.2 写入数据
- 调用 channel 的 read() 方法
- 调用 buffer 的 put() 方法
int readBytes = channel.read(buf);
// 或
buf.put((byte)127);
2.3 读取数据
- 调用 channel 的 write() 方法
- 调用 buffer 的 get() 方法
int writeBytes = channel.write(buf);
// 或
byte b = buf.get();
- get() 方法会让 position 读指针向后走,如果想重复读取数据
- 可以调用 rewind() 方法将 position 重新置为0
- 或者调用 get(int i) 方法获取 i 的内容,它不会移动读指针
2.4 读写模式切换
flip方法
:切换 buffer 为读模式clear方法
:切换 buffer 为写模式compact方法
:切换 buffer 为写模式
2.5 mark 和 reset
- mark是在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置
注意
rewind 和 flip 都会清除 mark 位置
2.6 字符串与 ByteBuffer 互转
// 字符串转换为byteBuffer
ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("你好");
ByteBuffer buffer2 = Charset.forName("utf-8").encode("你好");
// byteBuffer转换为字符串
ByteBuffer buffer3 = StandardCharsets.UTF_8.decode(buffer1);
System.out.println(buffer3.toString());
2.7 分散读取
// 分散读取,有一个文本文件 3parts.txt,内容:onetwothree
try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
// 使用如下方式读取,可以将数据填充至多个 buffer
FileChannel channel = file.getChannel();
ByteBuffer a = ByteBuffer.allocate(3);
ByteBuffer b = ByteBuffer.allocate(3);
ByteBuffer c = ByteBuffer.allocate(5);
channel.read(new ByteBuffer[]{a, b, c});
a.flip();
b.flip();
c.flip();
debug(a);
debug(b);
debug(c);
} catch (IOException e) {
e.printStackTrace();
}
2.8 合并写入
// 使用如下方式写入,可以将多个 buffer 的数据填充至 channel
try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
FileChannel channel = file.getChannel();
ByteBuffer d = ByteBuffer.allocate(4);
ByteBuffer e = ByteBuffer.allocate(4);
channel.position(11);
d.put(new byte[]{'f', 'o', 'u', 'r'});
e.put(new byte[]{'f', 'i', 'v', 'e'});
d.flip();
e.flip();
debug(d);
debug(e);
channel.write(new ByteBuffer[]{d, e});
} catch (IOException e) {
e.printStackTrace();
}
2.9 习题
题目
:网络上有多条数据发送给服务端,数据之间使用 \n 进行分隔,但由于某种原因这些数据在接收时,被进行了重新组合,例如原始数据有3条为- Hello,world\n
- I’m zhangsan\n
- How are you?\n
- 变成了下面的两个 byteBuffer (黏包,半包)
- Hello,world\nI’m zhangsan\nHo
- w are you?\n
public class NioDemo {
public static void main(String[] args) {
ByteBuffer source = ByteBuffer.allocate(32);
source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
split(source);
source.put("w are you?\nhaha!\n".getBytes());
split(source);
}
private static void split(ByteBuffer source) {
source.flip();
for (int i = 0; i < source.limit(); i++) {
if (source.get(i) == '\n') {
int capacity = i + 1 - source.position();
ByteBuffer target = ByteBuffer.allocate(capacity);
for (int j = 0; j < capacity; j++) {
target.put(source.get());
}
ByteBufferUtil.debugAll(target);
}
}
source.compact();
}
}
/**** ****/
// 工具类
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;
// Generate the lookup table for hex dump paddings
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();
}
// Generate the lookup table for the start-offset header in each row (up to 64KiB).
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();
}
// Generate the lookup table for byte-to-hex-dump conversion
for (i = 0; i < BYTE2HEX.length; i++) {
BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
}
// Generate the lookup table for byte dump paddings
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();
}
// Generate the lookup table for byte-to-char conversion
for (i = 0; i < BYTE2CHAR.length; i++) {
if (i <= 0x1f || i >= 0x7f) {
BYTE2CHAR[i] = '.';
} else {
BYTE2CHAR[i] = (char) i;
}
}
}
/**
* 打印所有内容
* @param buffer
*/
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);
}
/**
* 打印可读取内容
* @param buffer
*/
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;
// Dump the rows which have 16 bytes.
for (int row = 0; row < fullRows; row++) {
int rowStartIndex = (row << 4) + startIndex;
// Per-row prefix.
appendHexDumpRowPrefix(dump, row, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(" |");
// ASCII dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append('|');
}
// Dump the last row which has less than 16 bytes.
if (remainder != 0) {
int rowStartIndex = (fullRows << 4) + startIndex;
appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(HEXPADDING[remainder]);
dump.append(" |");
// Ascii dump
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);
}
}
文件编程
1、FileChannel
工作模式
:FileChannel 只能工作在阻塞模式下常用方法
获取
:通过 FileInputStream、FileOutputStream 或者 RandomAccessFile 来获取读取
:调用 read 方法写入
:调用 write 方法关闭
:使用 try 或调用 close 方法位置
:调用 position 方法文件大小
:调用 size 方法强制写入
:调用 force(true) 方法
传输数据
public class TestFileChannelTransferTo {
public static void main(String[] args) {
try (
FileChannel from = new FileInputStream("data.txt").getChannel();
FileChannel to = new FileOutputStream("to.txt").getChannel();
) {
// 效率高,底层会利用操作系统的零拷贝进行优化
long size = from.size();
// left 变量代表还剩余多少字节
for (long left = size; left > 0; ) {
System.out.println("position:" + (size - left) + " left:" + left);
left -= from.transferTo((size - left), left, to);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、Path
概述
:Path 用来表示文件路径,Paths 是工具类,用来获取 Path 实例常用方法
Path source = Paths.get("1.txt"); // 相对路径 使用 user.dir 环境变量来定位 1.txt
Path source = Paths.get("D:\\1.txt"); // 绝对路径 代表了 d:\1.txt
Path projects = Paths.get("d:\\data", "projects"); // 代表了 d:\data\projects
Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
System.out.println(path);
System.out.println(path.normalize()); // 正常化路径
3、Files
3.1 检查文件是否存在
Path path = Paths.get("demo/abc.txt");
System.out.println(Files.exists(path));
3.2 创建目录
// 创建一级目录,如果目录已存在或他去多级目录,会抛异常
Path path = Paths.get("demo/d1");
Files.createDirectory(path);
// 创建多级目录
Path path = Paths.get("demo/d1");
Files.createDirectories(path);
3.3 拷贝文件
Path source = Paths.get("demo/data.txt");
Path target = Paths.get("demo/target.txt");
// 如果文件已经存在,会抛异常FileAlreadyExistsException
Files.copy(source,target);
// 如果希望用source覆盖掉target,需要用StandardCopyOption
Files.copy(source,target,StandardCopyOption.REPLACE_EXISTING);
3.4 移动文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");
// StandardCopyOption.ATOMIC_MOVE 保证文件移动的原子性
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
3.5 删除文件
Path target = Paths.get("demo/data.txt");
Files.delete(target)
3.6 删除目录
// 如果目录还有内容,会抛异常DirectoryNotEmptyException
Path target = Paths.get("demo/d1");
Files.delete(target);
3.7 遍历目录
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger dirCount = new AtomicInteger();
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
System.out.println(dir);
dirCount.incrementAndGet();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println(file);
fileCount.incrementAndGet();
return super.visitFile(file, attrs);
}
});
System.out.println(dirCount);
System.out.println(fileCount);
}
3.8 统计文件的数目
Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (file.toFile().getName().endsWith(".jar")) {
fileCount.incrementAndGet();
}
return super.visitFile(file, attrs);
}
});
System.out.println(fileCount);
3.9 删除多级目录
Path path = Paths.get("d:\\a");
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
Files.delete(dir);
return super.postVisitDirectory(dir, exc);
}
});
3.10 拷贝多级目录
long start = System.currentTimeMillis();
String source = "D:\\Snipaste-1.16.2-x64";
String target = "D:\\Snipaste-1.16.2-x64aaa";
Files.walk(Paths.get(source)).forEach(path -> {
try {
String targetName = path.toString().replace(source, target);
// 是目录
if (Files.isDirectory(path)) {
Files.createDirectory(Paths.get(targetName));
}
// 是普通文件
else if (Files.isRegularFile(path)) {
Files.copy(path, Paths.get(targetName));
}
} catch (IOException e) {
e.printStackTrace();
}
});
long end = System.currentTimeMillis();
System.out.println(end - start);
网络编程
1、TCP 编程
1.1 阻塞模式
概述
:阻塞模式下,相关方法会导致线程暂停。单线程下,阻塞方法相互影响,导致不能正常工作。多线程情况下,如果连接过多,上下文频繁切换导致性能降低。虽然可以使用线程池技术可以减少线程数和线程上下文切换,但很多会话长时间失活,会阻塞线程池中所有线程,因此,阻塞模式下不适合长连接,适合短连接案例
// 服务端
public class ServerDemo {
public static void main(String[] args) throws IOException {
final ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(8899));
ByteBuffer buffer = ByteBuffer.allocate(32);
while (true) {
final SocketChannel sc = ssc.accept(); // 阻塞方法
final int read = sc.read(buffer); // 阻塞方法
if (read != 0) {
buffer.flip();
ByteBufferUtil.debugAll(buffer);
buffer.clear();
}
}
}
}
// 客户端
public class ClientDemo {
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("127.0.0.1", 8899));
channel.write(ByteBuffer.wrap("Hello".getBytes()));
}
}
1.2 非阻塞模式
概述
:非阻塞模式下,相关方法不会让线程暂停。在没有连接建立和有数据可读取的时候,线程仍然在运行,白白浪费了 CPU,而且在数据复制过程中,线程实际还是阻塞的(AIO 改进的地方)案例
// 服务端
public class ServerDemo {
public static void main(String[] args) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(30);
List<SocketChannel> channels = new ArrayList<>();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(8866));
// 非阻塞模式
ssc.configureBlocking(false);
while (true) {
final SocketChannel sc = ssc.accept(); // 非阻塞模式下,该方法在没连接时会返回null
if (sc != null) {
sc.configureBlocking(false);
channels.add(sc);
System.out.println("连接建立...");
}
for (SocketChannel channel : channels) {
// 读取数据
int read = channel.read(buffer); // 非阻塞模式下,该方法在没数据时会返回0
if (read != 0) {
buffer.flip();
ByteBufferUtil.debugAll(buffer);
buffer.clear();
}
}
}
}
}
// 客户端
public class ClientDemo {
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("127.0.0.1", 8866));
// channel.write(ByteBuffer.wrap("Hello".getBytes()));
Scanner input = new Scanner(System.in);
System.out.print("请输入内容:");
while(input.hasNext()){
final String msg = input.next();
channel.write(ByteBuffer.wrap(msg.getBytes()));
System.out.print("请输入内容:");
}
}
}
3.2 多路复用模式
概述
:使用单线程配合 Selector 监控多个 Channel 的读写事件优点
- 事件发生时线程才去处理,从而避免非阻塞模式下所做无用功
- 节约了线程的数量
- 减少了线程上下文切换
基本使用
// 服务端
@Slf4j
public class ServerDemo3 {
public static void main(String[] args) {
try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
// 创建Selector
Selector selector = Selector.open();
// 设置channel为非阻塞模式
ssc.configureBlocking(false);
// 绑定事件
ssc.register(selector, SelectionKey.OP_ACCEPT);
// channel绑定端口号
ssc.bind(new InetSocketAddress(8080));
while (true) {
// 以阻塞方式监听channel直到绑定事件发生
final int count = selector.select();
log.info("channel连接数:{}", count);
final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
// 事件发生后,就会将相关的selectionKey放入selectedKeys集合,但不会在处理完后从集合中移除
iterator.remove();
if (key.isAcceptable()) { // 连接事件
final SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
final SelectionKey scKey = sc.register(selector, SelectionKey.OP_READ);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 300000; i++) {
sb.append("a");
}
ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
final int writeLen = sc.write(buffer);
log.info("实际写入字节数:{}", writeLen);
if (buffer.hasRemaining()) {
scKey.interestOps(scKey.interestOps() + SelectionKey.OP_WRITE);
scKey.attach(buffer);
}
} else if (key.isReadable()) { // 读事件
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
final int readLen = sc.read(buffer);
if (readLen == -1) {
// cancel()会取消注册在selector上的channel,并从集合中删除selectionKey,
// 后续不会再监听事件
key.cancel();
sc.close();
} else {
buffer.flip();
ByteBufferUtil.debugAll(buffer);
}
} else if (key.isWritable()) { // 写事件
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = (ByteBuffer) key.attachment();
final int writeLen = sc.write(buffer);
log.info("实际写入字节数:{}", writeLen);
buffer.clear();
if (!buffer.hasRemaining()) {
key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
key.attach(null);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 客户端
@Slf4j
public class ClientDemo3 {
public static void main(String[] args) throws IOException {
SocketChannel channel = SocketChannel.open();
Selector selector = Selector.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
channel.connect(new InetSocketAddress("localhost", 8080));
int count = 0;
while (true) {
selector.select();
final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
if (key.isConnectable()) {
log.info("连接状态:{}", channel.finishConnect());
} else if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
count += channel.read(buffer);
buffer.clear();
System.out.println(count);
}
}
}
}
}
优化
// BossEventLoop类
@Slf4j
public class BossEventLoop implements Runnable {
private Selector boss;
private WorkerEventLoop[] workers;
private volatile boolean start = false;
private final AtomicInteger index = new AtomicInteger();
public void register() {
if (!start) {
try {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(8899));
server.configureBlocking(false);
this.boss = Selector.open();
server.register(this.boss, SelectionKey.OP_ACCEPT, null);
initWorkers();
new Thread(this, "boss").start();
log.info("Boss Event Loop Start...");
this.start = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void initWorkers() {
this.workers = new WorkerEventLoop[2];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerEventLoop(i);
}
}
@Override
public void run() {
while (true) {
try {
this.boss.select();
final Iterator<SelectionKey> iterator = this.boss.selectedKeys().iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
final SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
this.workers[this.index.getAndIncrement() % this.workers.length].register(sc);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// WorkerEventLoop类
@Slf4j
public class WorkerEventLoop implements Runnable {
private Selector worker;
private volatile boolean start = false;
private int index;
private final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();
public WorkerEventLoop(int index) {
this.index = index;
}
public void register(SocketChannel sc) throws IOException {
if (!start) {
worker = Selector.open();
new Thread(this, "Worker" + index).start();
this.start = true;
}
tasks.add(() -> {
try {
SelectionKey key = sc.register(worker, 0, null);
key.interestOps(SelectionKey.OP_READ);
worker.selectNow();
} catch (Exception e) {
e.printStackTrace();
}
});
worker.wakeup();
}
@Override
public void run() {
while (true) {
try {
worker.select();
final Runnable task = tasks.poll();
if (task != null) {
task.run();
}
final Iterator<SelectionKey> iterator = worker.selectedKeys().iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
if (key.isReadable()) {
final SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(128);
try {
final int readLen = sc.read(buffer);
if (readLen == -1) {
key.cancel();
sc.close();
} else {
buffer.flip();
log.debug("{} message:", sc.getRemoteAddress());
ByteBufferUtil.debugAll(buffer);
}
} catch (Exception e) {
e.printStackTrace();
key.cancel();
sc.close();
}
}
iterator.remove();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 测试类
class EventLoopDemo {
public static void main(String[] args) {
new BossEventLoop().register();
}
}
2、UDP 编程
概述
:UDP 协议在传输数据前不需要建立连接,也避免了后续的断开连接,虽然不安全,但传输效率高。在数据报文超过缓存区大小时,多出来的数据会被抛弃基本使用
// 服务端
public class UdpServer {
public static void main(String[] args) {
try (DatagramChannel server = DatagramChannel.open()) {
server.bind(new InetSocketAddress(8899));
ByteBuffer buffer = ByteBuffer.allocate(32);
while(true){
server.receive(buffer);
buffer.flip();
ByteBufferUtil.debugAll(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 客户端
public class UdpClient {
public static void main(String[] args) {
try (DatagramChannel client = DatagramChannel.open()) {
final InetSocketAddress socketAddress = new InetSocketAddress("localhost", 8899);
final ByteBuffer buffer = Charset.defaultCharset().encode("Wood World");
client.send(buffer, socketAddress);
} catch (IOException e) {
e.printStackTrace();
}
}
}