0

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

4

1 回答 1

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();
于 2013-01-17T11:02:10.443 回答