Search code examples
androidudpdatagram

sending and receiving data to particular ip and port using UDP in android


Am trying to send data to particular ip address in particular port. but there is no response from the hardware device. below is my code. Same thing are work properly in iOS.but in androidd tt throwing socket timeout exception.

    DatagramSocket sendSoc = null;
            DatagramPacket packet = null;
            try {
                sendSoc = new DatagramSocket(WIPHONEPORT);//2739
                sendSoc.setBroadcast(true);
                sendSoc.setSoTimeout(5000);

                InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(deviceSignature.getDeviceIP()), WIPHONEPORT);

                byte[] ip = object.ToBuffer();
                Log.d("data", ip.length + "##" + Arrays.toString(ip));
                packet = new DatagramPacket(ip,
                        ip.length, address.getAddress(), address.getPort());

            } catch (IOException e) {
                Log.d("error","could not able to send packet");
                return;
            }


            WiphoneProp prop;
            boolean canLoop = true;
            int i = 0;
            ////////////
            while (canLoop) {
                try {

                    sendSoc.send(packet);
                    try {
                        byte buf[] = new byte[1024];
                        DatagramPacket pack = new DatagramPacket(buf, buf.length);
                        sendSoc.receive(pack);
                        if (pack.getData() != null) {
                            if (!pack.getAddress().equals(getLocalIp())) {
                                prop = new WiphoneProp(pack.getData());
                                prop.validate();
                                canLoop=false;
                                Log.d("bytearray", Arrays.toString(pack.getData()));
                                Log.d("address ", pack.getAddress().getHostAddress() + " @@ " + pack.getAddress().getHostName() + " @@ " + pack.getAddress().getCanonicalHostName());
                                Log.d("result", prop.getWiphoneName());

                            }
                        }
                    } catch (UnknownHostException e) {
                        Log.d("UnknownHostException", "UnknownHostException");


                    }
                } catch (IOException e) {
                    Log.d("SocException", "IOException");

                }
                i++;
            }

Please help me. If you are not clear comment here please.


Solution

  • I fixed this issue by using same DatagramSocket object for all request.