android上的UDP接收器

时间:2013-01-17 10:38:47

标签: android eclipse udp

我想在eclipse上执行一个udp接收器。但它不起作用。 udp发送器正常工作,数据包通过特定端口发送。但是模拟器无法通过udp发送方接收任何数据包。需要帮助。

1 个答案:

答案 0 :(得分:1)

我不知道你的场景是什么,但根据我的场景,我只是使用php脚本在我的系统(Windows 7)上设置UDP服务器,并使用以下代码成功发送并从android模拟器接收UDP数据包。

String receivedString="";

        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        sendData = stringToBeSended.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData,
                sendData.length, IPAddress, port);

        DatagramSocket clientSocket;
        try {
            clientSocket = new DatagramSocket();


            clientSocket.send(sendPacket);

            DatagramPacket receivePacket = new DatagramPacket(receiveData,
                    receiveData.length);
            clientSocket.receive(receivePacket);
            receivedString = new String(receivePacket.getData());
            clientSocket.close();
        } catch (SocketException e) {
            Log.v("SocketExceptionOccured", e.toString())
            e.printStackTrace();
        } catch (IOException e) {
            Log.v("IOExceptionOccured", e.toString())
            e.printStackTrace();
        }

        Toast.makeText(getBaseContext(), receivedString, Toast.LENGTH_LONG).show();