Client.java 1.9 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 = 8888;

    public static void main(String[] args) {
        try {
            SocketChannel clientChannel = SocketChannel.open();
            clientChannel.configureBlocking(false);
            clientChannel.connect(new InetSocketAddress(HOST, PORT));

            while (!clientChannel.finishConnect()) {
                // wait until connection is established
            }

            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);

            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();

            while (true) {
                String message = scanner.nextLine();
                buffer = ByteBuffer.wrap(message.getBytes());
                clientChannel.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}