Android UDP Client Server Example

A protocol is a set of rules.An IP(Internet Protocol means a set of rules for sending data from sender to receiver.A UDP(User Defined Protocol) uses transport layer which provides end-to-end connection between the application.

The transfer layer is divided into two types.They are

1.Connection-oriented protocols

2.Connection-less Protocol

In this tutorial am going to teach how to establish a UDP client server connection.

SOURCE CODE

images

STEP BY STEP

1.Create an android project

Refer:How to create an android project

2.Add the following UI elements into main.xml file

Refer:Android UI Form Widgets

       a) 1 Edit Text

     b) 1 Button

     c) 1 TextView

After adding the main.xml code will be as shown bellow

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

    <EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

        <requestFocus />
</EditText>

    <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send" />

    <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Communication History:"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

3.Copy and paste the code in the mainactivity  class

package com.androidituts.udp;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UdpActivity extends Activity implements OnClickListener{
public static final String SERVERIP = "127.0.0.1"; // ‘Within’ the emulator!
public static final int SERVERPORT = 4444;
public TextView text1;
public EditText input;
public Button btn;
public boolean start;
public Handler Handler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

text1=(TextView)findViewById(R.id.textView1);
input=(EditText)findViewById(R.id.editText1);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
start=false;
new Thread(new Server()).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) { }
new Thread(new Client()).start();
Handler = new Handler() {
@Override public void handleMessage(Message msg) {
String text = (String)msg.obj;
text1.append(text);
}
};
}

public class Client implements Runnable {
@Override
public void run() {
while(start==false)
{
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
updatetrack("Client: Start connectingn");
DatagramSocket socket = new DatagramSocket();
byte[] buf;
if(!input.getText().toString().isEmpty())
{
buf=input.getText().toString().getBytes();
}
else
{
buf = ("Default message").getBytes();
}
DatagramPacket packet = new DatagramPacket(buf,

              buf.length, serverAddr, SERVERPORT);
updatetrack("Client: Sending ‘" + new String(buf) + "’n");
socket.send(packet);
updatetrack("Client: Message sentn");
updatetrack("Client: Succeed!n");
} catch (Exception e) {
updatetrack("Client: Error!n");
}
}
}
public class Server implements Runnable {

@Override
public void run() {
while(start==false)
{
}
try {
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
byte[] buf = new byte[17];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received: ‘" + new String(packet.getData()) + "’n");
updatetrack("Server: Succeed!n");
} catch (Exception e) {
updatetrack("Server: Error!n");
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
start=true;
}
public void updatetrack(String s){
Message msg = new Message();
String textTochange = s;
msg.obj = textTochange;
Handler.sendMessage(msg);
}

}

4.Add internet permission

Refer:How to add internet permission

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>

    <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".UdpActivity"
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>

5.Run the android application.

6.Result is shown bellow.

udp1

udp2