温馨提示×

温馨提示×

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

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

Java NIO如何进行网络编程

发布时间:2025-09-30 23:24:34 来源:亿速云 阅读:119 作者:小樊 栏目:编程语言

Java NIO(New I/O)是一个用于进行网络编程的API,它提供了非阻塞I/O操作的能力,使得开发者可以更高效地处理网络通信。Java NIO的核心组件包括Channels、Buffers和Selectors。下面是一个简单的Java NIO网络编程示例,包括一个服务器端和一个客户端。

服务器端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        // 创建一个Selector
        Selector selector = Selector.open();

        // 创建一个ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8888));
        serverSocketChannel.configureBlocking(false);

        // 将ServerSocketChannel注册到Selector上,监听ACCEPT事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            // 阻塞等待事件发生
            selector.select();

            // 获取所有已选择键的集合
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectedKeys.iterator();

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();

                if (key.isAcceptable()) {
                    // 处理ACCEPT事件
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    // 处理READ事件
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = client.read(buffer);

                    if (bytesRead > 0) {
                        buffer.flip();
                        byte[] data = new byte[buffer.remaining()];
                        buffer.get(data);
                        String message = new String(data).trim();
                        System.out.println("收到消息: " + message);

                        // 发送响应
                        String response = "服务器已收到: " + message;
                        ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
                        client.write(responseBuffer);
                    } else if (bytesRead == -1) {
                        client.close();
                    }
                }

                iterator.remove();
            }
        }
    }
}

客户端

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) throws IOException {
        // 创建一个SocketChannel
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8888));

        // 发送消息
        String message = "你好,服务器!";
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        socketChannel.write(buffer);

        // 接收响应
        buffer.clear();
        int bytesRead = socketChannel.read(buffer);
        if (bytesRead > 0) {
            buffer.flip();
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            String response = new String(data).trim();
            System.out.println("收到响应: " + response);
        }

        socketChannel.close();
    }
}

在这个示例中,服务器端监听8888端口,等待客户端连接。当客户端连接时,服务器端读取客户端发送的消息,并发送一个响应。客户端连接到服务器,发送一条消息,然后接收服务器的响应。

这个示例展示了Java NIO的基本用法,实际应用中可能需要处理更多的细节,例如异常处理、多线程处理等。

向AI问一下细节

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

AI
助
手