1

我想从我的笔记本电脑向安卓设备发送一个 udp 数据包,我为此编写了一个简单的应用程序,但它不起作用,我认为我一直使用的端口(5554)是问题所在。代码:

`私人无效runUdpServer()

    EditText RecieveText = (EditText) findViewById(R.id.editText1);
    EditText check = (EditText) findViewById(R.id.editText2);
    String lText;
    byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
    DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
    DatagramSocket ds = null;
    RecieveText.setText("try1");
    try {

RecieveText.setText("try2"); ds = new DatagramSocket(UDP_SERVER_PORT); // i think the problem is here
//disable timeout for testing
if (ds != null){RecieveText.setText("connected");}
否则 {RecieveText.setText("未连接");}

        RecieveText.setText("try");

ds.receive(dp); lText = new String(lMsg, 0, dp.getLength()); Log.i("UDP packet received", lText); RecieveText.setText(lText); check.setText("port opened"); } catch (SocketException e) {`` check.setText("SocketException"); e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
        check.setText("port didn't open");

    } finally {
        if (ds != null) {
            ds.close();
            RecieveText.setText("not connected1");
        }
        else {RecieveText.setText("not connected1");}
    }
    check.setText("end");
     if (ds != null){RecieveText.setText("connected");}            

else {RecieveText.setText("not connected");} } }

4

1 回答 1

0

我不认为这是一个端口问题...打印您的错误日志以更好地了解失败......任何方式尝试这个......不检查任何错字......另外请记住,任何网络任务最好是在异步任务中......

    int port =1855; ///any port that you want > 1024
    DatagramSocket socket = null;
    try {
        socket = new DatagramSocket(port);
    } catch (SocketException e) {
        e.printStackTrace();
    }
    try {
        socket.setBroadcast(true);
    } catch (SocketException e) {
        e.printStackTrace();
    }


    //////send socket
    int eport = 1616;
    InetAddress eip = null;
    try {
        eip = InetAddress.getByName("192.168.1.1");  ////SERVER IP ADDRESS 
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }


    DatagramSocket esocket = null;
    try {
        esocket = new DatagramSocket(eport);
    } catch (SocketException e) {
        e.printStackTrace();
    }

///发送

   byte[] send= new byte[60*1024];
     DatagramPacket send_packet = new DatagramPacket(send, send.length);


    try {
        socket.send(send_packet);
    } catch (IOException e) {
        e.printStackTrace();
    }

//////开始接收 while(true) {

        byte[] message = new byte[60*1024];
        DatagramPacket recv_packet = new DatagramPacket(message, message.length);


        try {
            socket.receive(recv_packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    ///Do something whit recv_packet
}
于 2015-07-11T15:06:06.500 回答