UDP server running on android for LAN


i have server and clients running in the LAN,but my server don't accept more than one message from client app. in LAN, what code shall i put in while loop in order to accept as many messages as i send from client app ? My server class is:

 public class MainActivity extends Activity {
private Boolean shouldRestartSocketListen=true;
TextView tv1;
//MulticastLock lock;
static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;
public void onCreate(Bundle savedInstanceState) {


       //   lock.release();

 private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
    byte[] recvBuf = new byte[15000];
    if (socket == null || socket.isClosed()) {
        socket = new DatagramSocket(port, broadcastIP);
    DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
    Log.e("UDP", "Waiting for UDP broadcast");

    String senderIP = packet.getAddress().getHostAddress();
    String message = new String(packet.getData()).trim();

//  Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);

    //  broadcastIntent(senderIP, message);

private void broadcastIntent(String senderIP, String message) {
    Intent intent = new Intent(MainActivity.UDP_BROADCAST);
    intent.putExtra("sender", senderIP);
    intent.putExtra("message", message);
       Thread UDPBroadcastThread;

void startListenForUDPBroadcast() {
    UDPBroadcastThread = new Thread(new Runnable() {
        public void run() {
            try {
                InetAddress broadcastIP = InetAddress.getByName(""); // //
                Integer port = 11111;
                while (shouldRestartSocketListen) {
                    listenAndWaitAndThrowIntent(broadcastIP, port);
                //if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
            } catch (Exception e) {
                Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());

void stopListen() {
    shouldRestartSocketListen = false;

public void onCreate() {


public void onDestroy() {
public IBinder onBind(Intent intent) {
    return null;


Don't close the socket unless you want to stop listening (put it outside your while loop).

I've tried using UDPFlood v2.0 from McAfee, with the socket.close() like you have it, you will miss messages as soon there are more than ~5 packets per second (depending how fast your other tasks are). The messages get buffered in your socket (OS) but you discard them by closing it.

By : PhilW

This video can help you solving your question :)
By: admin