2

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?

Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
sajith
  • 2,564
  • 8
  • 39
  • 57
  • What output are you expecting and why? – Dojo Apr 15 '12 at 05:39
  • i want to retrieve the original message "abc",which i added into the DatagramPacket,my problem is i cant retrieve the string instead i getting its binary value – sajith Apr 15 '12 at 06:02

2 Answers2

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.

Torious
  • 3,364
  • 17
  • 24
  • This ignores the transmitted length, and so it will give you a whole lot of trailing nulls. It's also five or six lines of code where one would do. – user207421 Jan 07 '17 at 05:33
1

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

Giang Phan
  • 534
  • 7
  • 15