Java NIO

发布时间 2023-04-15 22:11:23作者: xiaomu2023

 

 

 Server 服务端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
 
public class NioServer {
    public static void main(String[] args) {
        try {
            // 创建ServerSocketChannel并打开Selector
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            Selector selector = Selector.open();
            // 绑定端口并注册接收连接事件
            serverSocketChannel.socket().bind(new InetSocketAddress(8080));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务器已启动,监听端口8080...");
            // 处理Selector事件
            while (true) {
                if (selector.select(1000) == 0) {
                    // 没有事件发生,继续监听
                    continue;
                }
                // 处理发生的事件
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        // 有新连接,注册读事件
                        ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel clientChannel = serverChannel.accept();
                        clientChannel.configureBlocking(false);
                        clientChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                        System.out.println("客户端" + clientChannel.getRemoteAddress() + "已连接");
                    }
                    if (selectionKey.isReadable()) {
                        // 处理读事件
                        SocketChannel clientChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                        clientChannel.read(buffer);
                        System.out.println("从" + clientChannel.getRemoteAddress() + "收到消息:" + new String(buffer.array(), 0, buffer.position()));
                    }
                    // 从ready集合中移除事件
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

client 客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
 
public class NioClient {
    public static void main(String[] args) {
        try {
            // 创建SocketChannel并连接
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
            socketChannel.configureBlocking(false);
            // 向服务器发送消息
            ByteBuffer buffer = ByteBuffer.wrap("Hello, Server".getBytes());
            socketChannel.write(buffer);
            System.out.println("消息已发送:" + new String(buffer.array()));
            // 接收服务器返回的消息
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(readBuffer) == 0) {
                // 等待服务器响应
            }
            System.out.println("收到服务器响应:" + new String(readBuffer.array(), 0, readBuffer.position()));
            // 关闭连接
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

参考: