Java 套接字服务器-客户端 2 方式聊天程序未获得预期结果

A Java socket Server-Client 2 way chat program does not get expected result

我是 Java NIO 的新手,我正在使用 NIO2 编写一个简单的服务器-客户端 2 路通信程序。服务器和客户端正在本地 运行ning。我无法得到我预期的结果,有人可以帮忙检查一下代码吗?非常感谢。

服务器端:

public class Server 
{
    public static void main( String[] args )
    {
        try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()) {

            server.bind(new InetSocketAddress("127.0.0.1", 2001));
            Future<AsynchronousSocketChannel> acceptCon = server.accept();
            AsynchronousSocketChannel client = acceptCon.get(20, TimeUnit.SECONDS);

            if ((client != null) && (client.isOpen())) {
                Thread.sleep(50); // *** if I do not sleep 50 milsec here, I will get empty string
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                Future<Integer> readval = client.read(buffer);
                String msg = new String(buffer.array()).trim();
                System.out.println("Received from client: " + msg);

                readval.get();
                buffer.flip();
                String str = "I am fine! Thanks.";

                Future<Integer> writeVal = client.write(ByteBuffer.wrap(str.getBytes()));
                System.out.println("Writing back to client: " + str);
                writeVal.get();
                buffer.clear();
            }
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class Client 
{
    public static void main( String[] args )
    {
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        try (AsynchronousSocketChannel client = AsynchronousSocketChannel.open()) {

            Future<Void> result = client.connect(new InetSocketAddress("127.0.0.1", 2001));
            result.get();

            String str = "Hello! How are you?";
            ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
            Future<Integer> writeval = client.write(buffer);
            System.out.println("Writing to server: " + str);

            writeval.get();

            buffer.flip(); 


            Thread.sleep(100); // If I do not sleep 100 milsec here, most of the time, I will get empty string for svrMsg
            Future<Integer> readval = client.read(readBuffer);

            String svrMsg = new String(readBuffer.array()).trim();
            System.out.println("Received from server: " + svrMsg);
            readval.get();
            readBuffer.clear();
            buffer.clear();
        } catch (ExecutionException | IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("Disconnected from the server.");
        }
    }
}

我希望得到这样的东西: 服务器:

Received from client: Hello! How are you?
Writing back to client: I am fine! Thanks.

客户:

Writing to server: Hello! How are you?
Received from server: I am fine! Thanks.

但是,我得到了:

Received from client: Hello! How are you? | (If do not use sleep, it is empty string here)
Writing back to client: I am fine! Thanks.

客户:

Writing to server: Hello! How are you?
Received from server: I am fine! Thanks.(If do not use sleep, empty string here)

我的问题是: 1. 我正在使用Eclipse,当我通过断点调试服务器和客户端项目时,我得到了预期的结果。但是当我运行服务器和客户端时,在客户端,如果我不使用Thread.sleep(100),它会显示"Received from server:"的空字符串,为什么? 2. 对于服务器端,如果我不休眠 50 毫秒,大多数时候 "Received from client: " 的输出也将是空字符串,有什么提示吗?

非常感谢你们的帮助。

client.read(buffer); 是一个异步操作。 get 对未来的调用确保操作已成功完成。

ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> readval = client.read(buffer);
readval.get();
String msg = new String(buffer.array()).trim();
System.out.println("Received from client: " + msg);