How to retrieve String from DatagramPacket [duplicate]

安稳与你 提交于 2019-12-14 02:12:57

问题


The following code prints

[B@40545a60,[B@40545a60abc exp 

But I want to print abc, so that I can retrieve the correct message from the receiving system.

public class Operation {
InetAddress ip;
DatagramSocket dsock;
DatagramPacket pack1;
byte[] bin,bout;
WifyOperation(InetAddress Systemip)
{
    ip=Systemip;
    try {
        dsock=new DatagramSocket();

        } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

}

void sendbyte()
{
    String senddata="abc"; 
    bout=senddata.getBytes();
    pack1=new DatagramPacket(bout,bout.length,ip,3322);
    try {
        dsock.send(pack1);
        Log.d(pack1.getData().toString(),"abc exp");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

How can I retrieve string instead of byte from the packet pack1?


回答1:


New answer based on comment:

Indeed, my old answer was incorrect. Update:

String str = new String(
    pack1.getData(),
    pack1.getOffset(),
    pack1.getLength(),
    StandardCharsets.UTF_8 // or some other charset
);

Old answer:

Do something like:

byte[] data = pack1.getData();
InputStreamReader input = new InputStreamReader(
    new ByteArrayInputStream(data), Charset.forName("UTF-8"));

StringBuilder str = new StringBuilder();
for (int value; (value = input.read()) != -1; )
    str.append((char) value);

This assumes the byte data represents (just) UTF-8 text, which may not be the case.




回答2:


You can try: String msg = new String(pack1.getData(), pack1.getOffset(), pack1.getLength());



来源:https://stackoverflow.com/questions/10159732/how-to-retrieve-string-from-datagrampacket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!