How to receive data using UDP in Android?

前端 未结 2 888
悲&欢浪女
悲&欢浪女 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";
    
    
    }
    

提交回复
热议问题