Packet loss while receiving UDP broadcast in android device

后端 未结 5 1636
旧时难觅i
旧时难觅i 2021-01-05 03:46

For receiving UDP broadcast packets from the server to an android device, i used a service class and listen for packets in a thread. It receives the packet successfully. The

5条回答
  •  被撕碎了的回忆
    2021-01-05 04:10

    With reference to above explanation by me following changes you can make to make code behave according to requirement

    I suppose you can make following changes to make your problem code work instead of creating socket into listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port ) method create it in startListenForUdpBroadcast() as follows

    socket = new DatagramSocket(port, broadcastIP);
    socket.setBroadcast(true);
    while (shouldRestartSocketListen) {
         listenAndWaitAndThrowIntent(broadcastIP, port, socket);
    }
    

    Now you also need to change implementation of listenAndWaitAndThrowIntent method as follows

    private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, 
    Integer port, DatagramSocket socket) throws Exception {
        byte[] recvBuf = new byte[64000];
        //socket.setSoTimeout(1000);
        //change value of condition in for loop to desired number of packets you would like to receive in below example it is 2 so it captures two packets
        for (int i=0 ; i <= 2 ; i++ ){
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
    
        socket.receive(packet);
        messQueue.add(packet);
        }
    
    }
    

    Try this it should work !! it might help

提交回复
热议问题