How to receive data using UDP in Android?

前端 未结 2 874
悲&欢浪女
悲&欢浪女 2020-12-19 22:48

I use the following code to receive the data from a particular port. It\'s not working in Android. But sending data to particular port is working fine.

publi         


        
相关标签:
2条回答
  • 2020-12-19 23:00

    Used Port numbers

    Create Datagram packet

     try {
                mDataGramSocket = new DatagramSocket(Config.PORT_NUMBER);
                mDataGramSocket.setReuseAddress(true);
                mDataGramSocket.setSoTimeout(1000);
            } catch (SocketException e) {
                e.printStackTrace();
            } 
    

    Call below function through AsyncTask

    Create Function to receive infinitely

    public void receive() {
    
    
        String text;
    
        byte[] message = new byte[1500];
        DatagramPacket p = new DatagramPacket(message, message.length);
    
    
    
        try {
    
    
            while (true) {  // && counter < 100 TODO
                // send to server omitted
                try {
                    mDataGramSocket.receive(p);
                    text = new String(message, 0, p.getLength());
                    // If you're not using an infinite loop:
                    //mDataGramSocket.close();
    
                } catch (SocketTimeoutException | NullPointerException e) {
                    // no response received after 1 second. continue sending
    
                    e.printStackTrace();
                }
            }
    
    
        } catch (Exception e) {
    
            e.printStackTrace();
            // return "error:" + e.getMessage();
            mReceiveTask.publish("error:" + e.getMessage());
        }
    
        // return "out";
    
    
    }
    
    0 讨论(0)
  • 2020-12-19 23:16

    If you are using the emulator you may need setup redirects, remember the emulator is behind a virtual router.

    In other words, type these commands in;

    telnet localhost 5554
    redir add udp:9876:9876
    

    and try again.

    0 讨论(0)
提交回复
热议问题