Fatih POLAT
Fatih POLAT

Reputation: 167

How to make a UDP connection in android

I'm trying to make a connection between my galaxy tab and my laptop. So I'm trying to run server activity on my laptop and client activity on my tab, but it doesn't work. Here is the server and client code. Where is the mistake?

SERVER:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView txt = (TextView)findViewById(R.id.textView1);

    int port = 12345;
    byte [] message = new byte [1500];
    DatagramPacket p = new DatagramPacket (message,message.length);
    try {
        InetAddress serveraddr = InetAddress.getByName("192.168.1.116");
        DatagramSocket s = new DatagramSocket (port,serveraddr);
        while (true){
            s.receive(p);
            String text = new String (message,0,p.getLength());
            txt.setText(text);
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

CLIENT:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText edt = (EditText)findViewById(R.id.editText1);
    Button btn = (Button)findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            String msg = edt.getText().toString();
            int port = 12345;
            try {
                DatagramSocket s = new DatagramSocket();
                InetAddress local  = InetAddress.getByName("192.168.1.116");
                int msg_lenght = msg.length();
                byte []message = msg.getBytes();
                DatagramPacket p = new DatagramPacket(message,msg_lenght,local,port);
                s.send(p);
            } catch (SocketException e) {                   
                e.printStackTrace();
            } catch (UnknownHostException e) {                  
                e.printStackTrace();
            } catch (IOException e) {               
                e.printStackTrace();
            }               
        }
    });
}

Here is the log:

09-17 23:49:55.190: D/dalvikvm(5892): Late-enabling CheckJNI 09-17 23:49:55.690: D/CLIPBOARD(5892): Hide Clipboard dialog at Starting input: finished by someone else... ! 09-17 23:49:59.590: D/AndroidRuntime(5892): Shutting down VM 09-17 23:49:59.590: W/dalvikvm(5892): threadid=1: thread exiting with uncaught exception (group=0x40c4f1f8) 09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL EXCEPTION: main 09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 09-17 23:49:59.590: E/AndroidRuntime(5892): at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) 09-17 23:49:59.590: E/AndroidRuntime(5892): at libcore.io.IoBridge.sendto(IoBridge.java:463) 09-17 23:49:59.590: E/AndroidRuntime(5892): at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182) 09-17 23:49:59.590: E/AndroidRuntime(5892): at java.net.DatagramSocket.send(DatagramSocket.java:307) 09-17 23:49:59.590: E/AndroidRuntime(5892): at com.example.udpclient.MainActivity$1.onClick(MainActivity.java:36) 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.view.View.performClick(View.java:3620) 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.view.View$PerformClick.run(View.java:14322) 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.Handler.handleCallback(Handler.java:605) 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.Handler.dispatchMessage(Handler.java:92) 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.os.Looper.loop(Looper.java:137) 09-17 23:49:59.590: E/AndroidRuntime(5892): at android.app.ActivityThread.main(ActivityThread.java:4507) 09-17 23:49:59.590: E/AndroidRuntime(5892): at java.lang.reflect.Method.invokeNative(Native Method) 09-17 23:49:59.590: E/AndroidRuntime(5892): at java.lang.reflect.Method.invoke(Method.java:511) 09-17 23:49:59.590: E/AndroidRuntime(5892): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978) 09-17 23:49:59.590: E/AndroidRuntime(5892): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 09-17 23:49:59.590: E/AndroidRuntime(5892): at dalvik.system.NativeStart.main(Native Method) 09-17 23:50:34.320: I/Process(5892): Sending signal. PID: 5892 SIG: 9

Upvotes: 4

Views: 23752

Answers (4)

Mr Phuc 87
Mr Phuc 87

Reputation: 174

Have 2 problems with your code

  1. Work with Network on Main thread (UI Thread)

09-17 23:49:59.590: E/AndroidRuntime(5892): FATAL EXCEPTION: main 09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException

  1. Loop while(true) on the Main thread:

    while(true) {
        s.receive(p);
        String text = new String (message,0,p.getLength());
        txt.setText(text);
    }
    

Upvotes: 0

Paul Alexander
Paul Alexander

Reputation: 2748

  • you cannot send udp packets on ui thread, so a new seperate thread must be created.

Just a quick solution...

create a udpOutputData string:
String udpOutputData;

create a new thread in your code:

    //-----UDP send thread
Thread udpSendThread = new Thread(new Runnable() {

        @Override
        public void run() {


                while (true) {  

                    try {
                        Thread.sleep(100);
                    } 

                    catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                        if (sendUdp == true) {

                            try {

                                // get server name
                                InetAddress serverAddr = InetAddress.getByName(outputIP);
                                Log.d("UDP", "C: Connecting...");

                                // create new UDP socket
                                DatagramSocket socket = new DatagramSocket();

                                // prepare data to be sent
                                byte[] buf = udpOutputData.getBytes();

                                // create a UDP packet with data and its destination ip & port
                                DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, broadcastPort);
                                Log.d("UDP", "C: Sending: '" + new String(buf) + "'");

                                // send the UDP packet
                                socket.send(packet);

                                socket.close();

                                Log.d("UDP", "C: Sent.");
                                Log.d("UDP", "C: Done.");


                            } 

                            catch (Exception e) {
                                Log.e("UDP", "C: Error", e);

                            }

                                try {
                                    Thread.sleep(100);
                                }

                                catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }


                                sendUdp = false;
                        }

                }
        }

});

create a method to call everytime you want to send some udp data:

    public void sendUdp(String udpMsg) {

       udpOutputData = udpMsg;
       sendUdp = true;
    }

call the method and pass a string for the output data everytime you want to send a udp packet:

String s = "hello from app";
sendUdp(s);

Upvotes: 0

MemLeak
MemLeak

Reputation: 4640

09-17 23:49:59.590: E/AndroidRuntime(5892): android.os.NetworkOnMainThreadException
09-17 23:49:59.590: E/AndroidRuntime(5892):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-17 23:49:59.590: E/AndroidRuntime(5892):     at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175)

You shouldn't do network or time intensiv operations in ui thread

See also: Android: NoClassDefFoundError for some app users or android developers information

Checkout: activity.runOnUi

Upvotes: 4

Fildor
Fildor

Reputation: 16148

You have an infinite loop in onCreate of the Server. You shouldn't! Create a thread for polling the socket.

Upvotes: 0

Related Questions