SoFunction
Updated on 2025-04-12

UDP programming example for Android


package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
 *
* UdpHelper Help Class
 *
* @author Chen Zherong
 *
 */
public class UdpHelper  implements Runnable {
public     Boolean IsThreadDisable = false;//Indicates whether the listening thread has terminated
    private static lock;
    InetAddress mInetAddress;
    public UdpHelper(WifiManager manager) {
         = ("UDPwifi");
    }
    public void StartListen()  {
// The port of UDP server listening
        Integer port = 8903;
// The received byte size cannot exceed this size
        byte[] message = new byte[100];
        try {
// Establish Socket Connection
            DatagramSocket datagramSocket = new DatagramSocket(port);
            (true);
            DatagramPacket datagramPacket = new DatagramPacket(message,
                    );
            try {
                while (!IsThreadDisable) {
// Prepare to receive data
("UDP Demo", "Prepare to Accept");
                     ();

                    (datagramPacket);
                    String strMsg=new String(()).trim();
                    ("UDP Demo", ()
                            .getHostAddress().toString()
                            + ":" +strMsg );();
                }
            } catch (IOException e) {//IOException
                ();
            }
        } catch (SocketException e) {
            ();
        }
    }
    public static void send(String message) {
        message = (message == null ? "Hello IdeasAndroid!" : message);
        int server_port = 8904;
("UDP Demo", "UDP send data:"+message);
        DatagramSocket s = null;
        try {
            s = new DatagramSocket();
        } catch (SocketException e) {
            ();
        }
        InetAddress local = null;
        try {
            local = ("255.255.255.255");
        } catch (UnknownHostException e) {
            ();
        }
        int msg_length = ();
        byte[] messageByte = ();
        DatagramPacket p = new DatagramPacket(messageByte, msg_length, local,
                server_port);
        try {
            (p);
            ();

        } catch (IOException e) {
            ();
        }
    }
    @Override
    public void run() {
            StartListen();
    }
}