如何从DatagramPacket类检索字符串 [英] How to retrieve String from DatagramPacket

查看:233
本文介绍了如何从DatagramPacket类检索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code打印

[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();
    }
}
}

我怎么可以检索字符串,而不是字节的数据包 PACK1

推荐答案

做这样的事情:

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);

此假定字节数据重新presents(恰好)UTF-8文本,这可能并非如此。

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

这篇关于如何从DatagramPacket类检索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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