如何摆脱缓冲区的剩余空间?

2022-01-22 00:00:00 sockets networking udp java datagram

我有一个使用数据报套接字交换消息的服务器-客户端应用程序.我最初将缓冲区大小设置为 1024 字节,因为我不知道消息的长度.当我发送小于 1024 字节的内容时,我的字符串的其余部分显示为一些奇怪的字符(空字符或者我不确定它们是如何被调用的).这是一个屏幕:

I have a server-client application that is using a datagram socket to exchange messages. I have initially set the buffer size to be 1024 bytes because I dont know the length of the messages. When I send something that is shorter than 1024 bytes I get the rest of my string displayed as some weird characters (null characters or I am not sure how they are called). Here is a screen:

客户端代码:byte[] buf = ("这是另一个数据包. ").getBytes();DatagramPacket packet = new DatagramPacket(buf, buf.length, inetAddress, serverport);socket.send(数据包)

Client code: byte[] buf = ("This is another packet. ").getBytes(); DatagramPacket packet = new DatagramPacket(buf, buf.length, inetAddress, serverport); socket.send(packet)

服务器代码:字节[] buf = 新字节[1024];DatagramPacket packet = new DatagramPacket(buf, buf.length);socket.receive(packet);

推荐答案

好的,所以我想出了一个适合我的解决方案:

Ok so I came up with a solution that worked for me:

    public String getRidOfAnnoyingChar(DatagramPacket packet){
        String result = new String(packet.getData());
        char[] annoyingchar = new char[1];
        char[] charresult = result.toCharArray();
        result = "";
        for(int i=0;i<charresult.length;i++){
            if(charresult[i]==annoyingchar[0]){
                break;
            }
            result+=charresult[i];
        }
        return result;
    }

使用 ByteArrayOutputStream 存在更好的解决方案,可在此处找到:如何重新初始化数据包的缓冲区?

There exists a better solution using ByteArrayOutputStream which can be found here: How to reinitialize the buffer of a packet?

相关文章