简体   繁体   中英

how to Receive UDP packets, when it comes from server? for android java

I have used a thread for UDP receive packet. When I am sending a packet to that particular IP, where the UDP receive program runs. The application will be stopped unfortunately. Then if I remove the thread called new Thread(new Runnable()) and public void run the application will run good, but only one data has received. My intention is to receive data at the receiver end continuously, when data comes. please acknowledge me.

udpserver.java:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class UdpServer extends Activity {
/** Called when the activity is first created. */
private TextView data;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    data = (TextView) findViewById(R.id.textView);

        runUdpServer();

}
private static final int UDP_SERVER_PORT = 11111;
private static final int MAX_UDP_DATAGRAM_LEN = 1500;
private void runUdpServer() {
    new Thread(new Runnable() {
        public void run() {
            String lText;
            byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
            DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
            DatagramSocket ds=null;
            try {
                 ds = new DatagramSocket(UDP_SERVER_PORT);
                //disable timeout for testing
                //ds.setSoTimeout(100000);
                ds.receive(dp);
                lText = new String(dp.getData());
                Log.i("UDP packet received", lText);
                data.setText(lText);
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                if (ds != null) {
                    ds.close();
                }
            }
        }
    }).start();
}

This is a working snippet I am using to receive and parse UDP packets.

  try {
        int port = 11000;

        DatagramSocket dsocket = new DatagramSocket(port);
        byte[] buffer = new byte[2048];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        while (true) {

            dsocket.receive(packet);
            lText = new String(buffer, 0, packet.getLength());
            Log.i("UDP packet received", lText);
            data.setText(lText);

            packet.setLength(buffer.length);
        }
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace();
    }

You can setup a loop to read data from the udp socket.

try {
    ds = new DatagramSocket(UDP_SERVER_PORT);
    //disable timeout for testing
    //ds.setSoTimeout(100000);
    while (!ds.isClosed()) {
        ds.receive(dp);
        lText += new String(dp.getData());
        Log.i("UDP packet received", new String(dp.getData());
        runOnUiThread(new Runnable() {
            public void run() {
                data.setText(lText);
            }
        });
    }
} catch (SocketException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (ds != null) {
        ds.close();
    }
}

UPDATE : since the packet data is received in non-UI thread. Direct access to data.setText(lText) in worker thread is invalid.

try {
      DatagramSocket clientsocket=new DatagramSocket(9876);
      byte[] receivedata = new byte[1024];
      while(true)
      {
        DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
        Log.d("UDP", "S: Receiving...");
        clientsocket.receive(recv_packet);
        String rec_str = new String(recv_packet.getData());
        tv.setText(rec_str);
        Log.d(" Received String ",rec_str);
        InetAddress ipaddress = recv_packet.getAddress();
        int port = recv_packet.getPort();
        Log.d("IPAddress : ",ipaddress.toString());
        Log.d(" Port : ",Integer.toString(port));
      }
    } catch (Exception e) {
      Log.e("UDP", "S: Error", e);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM