UDP Client on Android

11,783

Solution 1

I found the solution for the problem

The problem was in the manifest

Here is my new code and my manifest

The main in wich I call the UDP_Client :

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    private TextView sceen = null;
    private Button launch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        sceen = (TextView)findViewById(R.id.textView1);
        launch = (Button)findViewById(R.id.udpbutton);
        launch.setOnClickListener(this); 

       launch.setOnClickListener((OnClickListener) this); 

    }
           public void onClick(View v) {
               //UDP Client erstellen
               UDP_Client Client = new UDP_Client();
               Client.Message = "Your message";
                    Client.NachrichtSenden();






           }


    }

The code of my UDP_Client

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;

public class UDP_Client 
{

    private InetAddress IPAddress = null;
    private String message = "Hello Android!" ;
    private AsyncTask<Void, Void, Void> async_cient;
    public String Message;


    @SuppressLint("NewApi")
    public void NachrichtSenden()
    {
        async_cient = new AsyncTask<Void, Void, Void>() 
        {
            @Override
            protected Void doInBackground(Void... params)
            {   
                DatagramSocket ds = null;

                try 
                {
                    byte[] ipAddr = new byte[]{ (byte) 192, (byte) 168,43, (byte) 157};
                    InetAddress addr = InetAddress.getByAddress(ipAddr);
                    ds = new DatagramSocket(5000);
                    DatagramPacket dp;                          
                    dp = new DatagramPacket(Message.getBytes(), Message.getBytes().length, addr, 50000);
                    ds.setBroadcast(true);
                    ds.send(dp);
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
                finally 
                {
                    if (ds != null) 
                    {   
                        ds.close();
                    }
                }
                return null;
            }

            protected void onPostExecute(Void result) 
            {
               super.onPostExecute(result);
            }
        };

        if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else async_cient.execute();
    }
}

The manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.udp_server"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I added the part of code in my manifest

hope that it will help someone in the future ;)

Solution 2

I think you miss this:

public void connect (InetAddress address, int port)

Of the DataGramSocket Object.

Try:

client_socket.connect(IPAddress, port);
client_socket.send(send_packet);
Share:
11,783
Abdel Z
Author by

Abdel Z

Updated on June 04, 2022

Comments

  • Abdel Z
    Abdel Z almost 2 years

    I have made an UDP Server on a Wi-Fi demo board and test it using and android App (UDP Sender). I created my own UDP client apps on Android, but it doesn't work.

    I created and configured well the socket port and the IPaddress but the app doesn't work and I don't know why.

    PS : In the manifest I added the uses-permission to access to the Wi-Fi

    her is my simple code

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class Udp_Client extends Activity {
    
    
        /** Called when the activity is first created. */
        TextView txt5,txt1;
        byte[] send_data = new byte[1024];
        Button hello;
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            txt1   = (TextView)findViewById(R.id.textView1); 
            txt5   = (TextView)findViewById(R.id.textView5); 
    
            hello = (Button) findViewById(R.id.button1);
    
    
    
    
    
    
            hello.setOnClickListener(new View.OnClickListener(){             
                public void onClick(View v) {                 
    
    
                    try {
                        client();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
    
                }  
    
             }); 
    
    
        }
    
    
        public void client() throws IOException{
    
                String str="Hello";
                int port = 50000;
             DatagramSocket client_socket = new DatagramSocket(port);
             InetAddress IPAddress =  InetAddress.getByName("192.168.0.1"); 
    
                            send_data = str.getBytes();
    
    
                DatagramPacket send_packet = new DatagramPacket(send_data,str.length(), IPAddress, port);
                //client_socket.setBroadcast(true);
                client_socket.send(send_packet);                      
    
    
                client_socket.close();
    
            }       
    
    }
    

    [1]: http://i.stack.imgur.com/aXPhf.png

  • Rene M.
    Rene M. over 9 years
    I havn't tested it and I'm not that UDP Socket expert ;)
  • Abdel Z
    Abdel Z over 9 years
    It's still not working even when I add the connect(IPAddress,port)
  • Rene M.
    Rene M. over 9 years
    Sorry I only had a small look on the API Docs and thought that it. Because I saw no initial connection between your client and the server.
  • Abdel Z
    Abdel Z over 9 years
    <uses-permission android:name="android.permission.INTERNET" />
  • Trake Vital
    Trake Vital about 3 years
    Damn this saved me man! I was constantly trying to use bind which is used instead for server sockets