使用 Java NIO 库实现非阻塞的客户端和服务器之间的通信

服务端

import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class Server {
    private static final int PORT = 8080;
    private static final Charset CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.socket().bind(new InetSocketAddress(PORT));
        serverChannel.configureBlocking(false);
        System.out.println("Listening on port " + PORT);

        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            int readyCount = selector.select();
            if (readyCount == 0) {
                continue;
            }

            for (SelectionKey key : selector.selectedKeys()) {
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel)key.channel();
                    SocketChannel client = server.accept();
                    System.out.println("Accepted new connection from " + client.getRemoteAddress());
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel client = (SocketChannel)key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = client.read(buffer);
                    if (bytesRead == -1) {
                        System.out.println("Connection closed by " + client.getRemoteAddress());
                        client.close();
                    } else if (bytesRead > 0) {
                        String message = new String(buffer.array(), 0, bytesRead, CHARSET);
                        System.out.println("Received message: " + message);
                        client.register(selector, SelectionKey.OP_WRITE, message);
                    }
                } else if (key.isWritable()) {
                    SocketChannel client = (SocketChannel)key.channel();
                    String message = (String)key.attachment();
                    ByteBuffer buffer = CHARSET.encode(message);
                    client.write(buffer);
                    System.out.println("Sent response to " + client.getRemoteAddress());
                    client.register(selector, SelectionKey.OP_READ);
                }
            }
            selector.selectedKeys().clear();
        }
    }
}

客户端

import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class Client {
    private static final String SERVER_ADDRESS = "localhost";
    private static final int PORT = 8080;
    private static final Charset CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws Exception {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(new InetSocketAddress(SERVER_ADDRESS, PORT));
        System.out.println("Connecting to server");

        Selector selector = Selector.open();
        channel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            int readyCount = selector.select();
            if (readyCount == 0) {
                continue;
            }

            for (SelectionKey key : selector.selectedKeys()) {
                if (key.isConnectable()) {
                    SocketChannel client = (SocketChannel)key.channel();
                    if (client.isConnectionPending()) {
                        client.finishConnect();
                    }
                    System.out.println("Connected to " + client.getRemoteAddress());
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_WRITE, "Hello from client");
                } else if (key.isWritable()) {
                    SocketChannel client = (SocketChannel)key.channel();
                    String message = (String)key.attachment();
                    ByteBuffer buffer = CHARSET.encode(message

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值