简体   繁体   中英

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(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. 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

ps 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM