Java原生Nio服务端与客户端的编写(待完善)

一、Nio服务端

public static void main(String[] args) throws IOException {
// 创建服务器
ServerSocketChannel server = ServerSocketChannel.open();
// 绑定端口
server.bind(new InetSocketAddress(6666));
// 设置为非阻塞IO
server.configureBlocking(false);
// 创建一个IO多路复用选择器
Selector selector = Selector.open();
// selector注册到channel上
server.register(selector, SelectionKey.OP_ACCEPT);
while (true){
/**
* 阻塞方法。返回值代表发生事件的通道个数
* 0 超时
* 1 错误
*/
int select = selector.select();
// 代码运行到此处,说明有可读,可写,可连接的channel
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
iterator.remove();
if (selectionKey.isAcceptable()) {
System.out.println("有人连接了。。。");
// 三次握手,进行连接
SocketChannel accept = server.accept();
accept.configureBlocking(false);
accept.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}

if (selectionKey.isReadable()) {
System.out.println("读取到数据。。。");
SocketChannel channel =(SocketChannel) selectionKey.channel();
ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
// 读取前清空buffer,清空上一个buffer
buffer.clear();
channel.read(buffer);
System.out.println(new String(buffer.array(),0,buffer.position(), StandardCharsets.UTF_8));
}

if (selectionKey.isWritable()) {
System.out.println("进入可写状态。。。");
// TODO 待编写
}
}
}
}

二、客户端的编写

public static void main(String[] args) throws IOException, InterruptedException {
SocketChannel client = SocketChannel.open();
client.connect(new InetSocketAddress(6666));
client.configureBlocking(false);

if (client.finishConnect()) {
while (true) {
Scanner sc = new Scanner(System.in);
String next = sc.next();
client.write(ByteBuffer.wrap(next.getBytes(StandardCharsets.UTF_8)));
}
}
}