在android中使用UDP向特定的ip和端口发送和接收数据

时间:2016-10-27 17:30:42

标签: android udp datagram

我试图将数据发送到特定端口的特定IP地址。但硬件设备没有响应。下面是我的代码。同样的事情在iOS中正常工作。但在androidd tt抛出套接字超时异常。

    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++;
            }

请帮帮我。如果你不清楚请在这里发表评论。

1 个答案:

答案 0 :(得分:0)

我通过对所有请求使用相同的DatagramSocket对象来修复此问题。