如何修复服务器的输出以使其正确显示来自客户端的消息?

How to fix the output of the server to make it display the messages from the client correctly?

向服务器发送消息的过程似乎是正确的,但是服务器没有显示它得到的数据。我怎样才能让它正常工作?

客户端:

void manageClient(){
    try(DatagramChannel datagramChannel = DatagramChannel.open();
        Scanner input = new Scanner(System.in)){
        datagramChannel.connect(socketAddress);
          while (true){
            ByteBuffer buf = ByteBuffer.allocate(512);
            String r = input.nextLine();
            buf.put(r.getBytes());
            datagramChannel.send(buf, socketAddress);
            messageToSend = null;
            buf.clear();
        }
    }
    catch (IOException e){
        e.printStackTrace();
        System.out.println("Cannot connect to the server!");
    }
}

服务器端:

    byte[] message = new byte[512];
DatagramPacket datagramPacket = new DatagramPacket(message, message.length);
void manageServer(){
    System.out.println("Waiting for the messages.");
    try(DatagramSocket datagramSocket = new DatagramSocket(7755)){
        try {
            while(true){
                datagramSocket.receive(datagramPacket);
                byte[] tobeString = datagramPacket.getData();
                String q = new String(tobeString, 0, tobeString.length);
                System.out.println("Server got: " + q);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("An error with input.");
        }
    }
    catch(SocketException e){
        System.out.println("A problem with connection occurred!");
    }
}

按下 "Enter" 后服务器不显示它收到的消息。

客户端的一些更改是解决方案:

while (true){
            ByteBuffer buf = ByteBuffer.allocate(512);
            r = input.nextLine();
            buf.put(r.getBytes());
            buf.flip();
            datagramChannel.send(buf, socketAddress);
            r = null;
            messageToSend = null;
            buf.clear();
        }

我更改了对字符串的引用并将 .flip() 方法添加到缓冲区。

希望对有类似问题的其他人有用。