Client.java 2.3 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 Client {
    private static final int BUFFER_SIZE = 1024;
    private static final String HOST = "localhost";
    private static final int PORT = 8877;

    public static void main(String[] args) {
        try {
            // 创建SocketChannel对象,连接服务器。
            SocketChannel clientChannel = SocketChannel.open();
            clientChannel.configureBlocking(false);
            clientChannel.connect(new InetSocketAddress(HOST, PORT));

            while (!clientChannel.finishConnect()) {
                // 如果连接未完成,等待连接完成。
            }

            System.out.println("Connected to server " + HOST + ":" + PORT);
            System.out.println("Enter your name:");

            // 读取用户输入的用户名,将其发送给服务器。
            Scanner scanner = new Scanner(System.in);
            String name = scanner.nextLine();
            ByteBuffer buffer = ByteBuffer.wrap(name.getBytes());
            clientChannel.write(buffer);

            // 创建一个新线程,使用SocketChannel的read()方法读取服务器发送的消息,并在控制台上显示。
            new Thread(() -> {
                while (true) {
                    try {
                        ByteBuffer receiveBuffer = ByteBuffer.allocate(BUFFER_SIZE);
                        int bytesRead = clientChannel.read(receiveBuffer);
                        if (bytesRead > 0) {
                            String message = new String(receiveBuffer.array()).trim();
                            System.out.println(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            // 在主线程中,读取用户输入的消息,使用SocketChannel的write()方法将其发送给服务器。
            while (true) {
                String message = scanner.nextLine();
                buffer = ByteBuffer.wrap(message.getBytes());
                clientChannel.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}