NIOClient.java 1.8 KB
package two;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NIOClient {
    public void start(String hostname, int port) throws IOException {
        // 创建SocketChannel
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(hostname, port));

        // 等待连接完成
        while (!socketChannel.finishConnect()) {
            // do nothing
        }

        System.out.println("Connected to server " + socketChannel.getRemoteAddress());

        // 循环读取用户输入,并发送到服务器
        Scanner scanner = new Scanner(System.in);

        new Thread(() -> {
            while (true) {
                try {
                    // 读取服务器发送的消息
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    int numRead = socketChannel.read(readBuffer);
                    if (numRead > 0) {
                        String receivedMessage = new String(readBuffer.array(), 0, numRead).trim();
                        System.out.println("Received message from server: " + receivedMessage);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        while (true) {
            if (scanner.hasNext()){
                String message = scanner.nextLine();
                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                socketChannel.write(buffer);
            }
        }

    }

    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.start("localhost", 8888);
    }
}