1、创建服务端
具体步骤请看代码注释,代码:
package com.ljfngu.nioSocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
/**
* <p>
* 基于NIO(no-blocking IO或者new IO)的Server服务端
* </p>
*
* @author ljfngu@163.com
* @version 1.0
* @date 2021/6/29 11:22
*/
public class NIOServer {
public static void main(String[] args) throws IOException {
new Thread(new NIOServerRunner(9999)).start();
}
static class NIOServerRunner implements Runnable {
private boolean running = true;
private boolean hasWrite = false;
private Selector selector;
private ServerSocketChannel serverSocketChannel;
NIOServerRunner(int port) throws IOException {
// 1、打开选择器
selector = Selector.open();
// 2、打开ServerSocketChannel通道
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);// 设置为非阻塞
// 3、绑定监听端口号
serverSocketChannel.socket().bind(new InetSocketAddress(port));
// 4、注册ServerSocketChannel通道准备接受客户端连接继续事件到选择器中
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("NIOServerRunner初始化完成,准备接受客户端连接");
}
@Override
public void run() {
while (running)