[英]Android UDP Socket - Receiving “Garbage”
OK so at the moment I am trying to create an Android Game, I have a Thread running which is fine. 好的,因此在我尝试创建一个Android游戏时,我正在运行一个很好的线程。
However I am unsure of how to determine how big the incoming buffer size, and how to read it. 但是我不确定如何确定传入缓冲区的大小以及如何读取它。
Currently this is my code: 目前,这是我的代码:
if(!thisPlayer.isHost)
{
byte[] incMsg = new byte[64];
try {
socket = new DatagramSocket(port);
//socket.setSoTimeout(10);
DatagramPacket packet = new DatagramPacket(incMsg, incMsg.length);
socket.receive(packet);
Log.d("Receiving Game Message", "Received"+incMsg.toString());
} catch (UnknownHostException err) {
Log.e("", "", err);
} catch (Exception err) {
Log.e("", "", err);
}
testString = incMsg.toString();
} else {
byte[] msg = "Game On".getBytes();
try {
String compIP = "192.168.1.102";
String ip;
if(thisPlayer.ipAddress.equals(compIP))
ip = "192.168.1.107";
else
ip = compIP;
InetAddress sendingIP = InetAddress.getByName(ip);
socket = new DatagramSocket(port);
DatagramPacket p = new DatagramPacket(msg, msg.length, sendingIP, 5130);
socket.send(p);
Log.d("Sending Game Message", "Sent");
socket.close();
} catch (UnknownHostException err) {
Log.e("", "", err);
} catch (Exception err) {
Log.e("", "", err);
}
}
socket.close();
This kind of works. 这种作品。 The Host is sending data.
主机正在发送数据。 The Client is receiving data (I have commented out the sotimeout and the thread continues, so I know its receving data).
客户端正在接收数据(我已注释掉超时并继续运行线程,因此我知道它正在接收数据)。
I convert the byte[] to a string and then display it. 我将byte []转换为字符串,然后显示它。 However what is displaying is "[B@448xxxx" where xxxx is a series of repeating numbers/letters.
但是,显示的是“ [B @ 448xxxx””,其中xxxx是一系列重复的数字/字母。
Unfortunately I am up to the point where I am getting frustrated and now clouded brain, and cannot think for the life of me where I have gone wrong. 不幸的是,我快要沮丧了,现在脑袋发白了,无法为我的生命思考我哪里出了问题。
TIA TIA
ps I have even tried making the receiving byte array the same size as the outgoing, without any luck :/ ps我什至尝试使接收字节数组的大小与输出字节数组的大小相同,而没有任何运气:/
As far as I know, this means a pointer to byte array. 据我所知,这意味着一个指向字节数组的指针。 You can't just assign it to string, instead, use
(new String(inMsg))
. 您不能只是将其分配给string,而是使用
(new String(inMsg))
。 Also, since you didn't initialize the array, you'll receive garbage after your received data (if shorter than the array). 另外,由于未初始化数组,因此在接收到的数据之后(如果比数组短)会收到垃圾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.