如何摆脱缓冲区的剩余空间? [英] How to get rid of the empty remaining of the buffer?

查看:22
本文介绍了如何摆脱缓冲区的剩余空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用数据报套接字交换消息的服务器-客户端应用程序.我最初将缓冲区大小设置为 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?

这篇关于如何摆脱缓冲区的剩余空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆