开发者

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.

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(thisPlaye开发者_JAVA百科r.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. However what is displaying is "[B@448xxxx" where xxxx is a series of repeating numbers/letters.

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

p.s. I have even tried making the receiving byte array the same size as the outgoing, without any luck :/


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)). Also, since you didn't initialize the array, you'll receive garbage after your received data (if shorter than the array).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜