温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java nio怎么写服务器

发布时间:2026-09-02 13:51:09 来源:亿速云 阅读:84 作者:小樊 栏目:编程语言

下面给你一个最基础、可直接运行的 Java NIO 服务器端示例,并配合关键概念说明,方便你理解。


一、Java NIO 服务器核心组件

Java NIO 主要用这几个类:

  • ServerSocketChannel:监听连接
  • SocketChannel:客户端连接
  • Selector:多路复用器(核心)
  • ByteBuffer:数据缓冲区

二、最简 NIO 服务器示例(单线程)

1️⃣ 服务器代码

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class NioServer {

    public static void main(String[] args) throws IOException {
        // 1. 打开 Selector
        Selector selector = Selector.open();

        // 2. 打开 ServerSocketChannel
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false); // 非阻塞
        serverChannel.bind(new InetSocketAddress(8080));

        // 3. 注册 Accept 事件
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("NIO Server started on port 8080");

        // 4. 事件循环
        while (true) {
            selector.select(); // 阻塞等待事件

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    // 有新连接
                    SocketChannel client = serverChannel.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                    System.out.println("Client connected");

                } else if (key.isReadable()) {
                    // 可读事件
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    int len = client.read(buffer);
                    if (len == -1) {
                        client.close();
                        continue;
                    }

                    buffer.flip();
                    byte[] data = new byte[buffer.remaining()];
                    buffer.get(data);
                    System.out.println("Received: " + new String(data));

                    // 回写客户端
                    buffer.rewind();
                    client.write(buffer);
                }
            }
        }
    }
}

三、运行方式

  1. 启动服务器
  2. telnetnc 测试:
telnet localhost 8080

输入内容 → 服务器回显


四、核心流程总结

ServerSocketChannel
        ↓ 注册 OP_ACCEPT
     Selector
        ↓ 事件触发
   SocketChannel
        ↓ 注册 OP_READ
     Selector
        ↓ 读/写数据

五、常见进阶点(你可以继续学)

  • ✅ 多线程 Reactor 模型
  • OP_WRITE 半包/粘包处理
  • ByteBuffer 堆外内存
  • ✅ Netty(生产级 NIO 封装)

如果你愿意,我可以:

  • 帮你写 Netty 版服务器
  • Reactor 线程模型
  • 写一个 聊天室示例
  • 或按你的业务场景定制

你想往哪块深入?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI