Simple udp server for android and get multi messages

后端 未结 1 556
野性不改
野性不改 2021-02-10 01:36

I write simple method for udp server:

 private void runUdpServer() {
        String message;
        byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
        Da         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-10 02:21

    Put the code you have into a loop, and put this loop into its own thread so that it doesn't block the UI thread.

    Use runOnUiThread() to update the UI from this new thread.

    Example:

    private MyDatagramReceiver myDatagramReceiver = null;
    
    protected void onResume() {
        myDatagramReceiver = new MyDatagramReceiver();
        myDatagramReceiver.start();
    }
    
    protected void onPause() {
        myDatagramReceiver.kill();
    }
    
    private class MyDatagramReceiver extends Thread {
        private boolean bKeepRunning = true;
        private String lastMessage = "";
    
        public void run() {
            String message;
            byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
            DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);
    
            try {
                DatagramSocket socket = new DatagramSocket(UDP_SERVER_PORT);
    
                while(bKeepRunning) {
                    socket.receive(packet);
                    message = new String(lmessage, 0, packet.getLength());
                    lastMessage = message;
                    runOnUiThread(updateTextMessage);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
    
            if (socket != null) {
                socket.close();
            }
        }
    
        public void kill() { 
            bKeepRunning = false;
        }
    
        public String getLastMessage() {
            return lastMessage;
        }
    }
    
    private Runnable updateTextMessage = new Runnable() {
        public void run() {
            if (myDatagramReceiver == null) return;
            textMessage.setText(myDatagramReceiver.getLastMessage());
        }
    };
    

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