Android Datagram/Udp Server Example

Posted on

I posted “Java Datagram/UDP Server too Client, run on raspberry Pi” on my about other blogspot. And lastly post service demo “Android Datagram/UDP Client example“. This post service demo a Datagram/UDP Server run on Android.


MainActivity.java

package com.blogspot.android_er.androidudpserver;  import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView;  import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Date; import java.util.Enumeration;  world cast MainActivity extends AppCompatActivity {      somebody lastly static String TAG = MainActivity.class.getSimpleName();      TextView infoIp, infoPort;     TextView textViewState, textViewPrompt;      static lastly int UdpServerPORT = 4445;     UdpServerThread udpServerThread;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         infoIp = (TextView) findViewById(R.id.infoip);         infoPort = (TextView) findViewById(R.id.infoport);         textViewState = (TextView)findViewById(R.id.state);         textViewPrompt = (TextView)findViewById(R.id.prompt);          infoIp.setText(getIpAddress());         infoPort.setText(String.valueOf(UdpServerPORT));     }      @Override     protected void onStart() {         udpServerThread = novel UdpServerThread(UdpServerPORT);         udpServerThread.start();         super.onStart();     }      @Override     protected void onStop() {         if(udpServerThread != null){             udpServerThread.setRunning(false);             udpServerThread = null;         }          super.onStop();     }      somebody void updateState(final String state){         runOnUiThread(new Runnable() {             @Override             world void run() {                 textViewState.setText(state);             }         });     }      somebody void updatePrompt(final String prompt){         runOnUiThread(new Runnable() {             @Override             world void run() {                 textViewPrompt.append(prompt);             }         });     }      somebody cast UdpServerThread extends Thread{          int serverPort;         DatagramSocket socket;          boolean running;          world UdpServerThread(int serverPort) {             super();             this.serverPort = serverPort;         }          world void setRunning(boolean running){             this.running = running;         }          @Override         world void run() {              running = true;              travail {                 updateState("Starting UDP Server");                 socket = novel DatagramSocket(serverPort);                  updateState("UDP Server is running");                 Log.e(TAG, "UDP Server is running");                  while(running){                     byte[] buf = novel byte[256];                      // have asking                     DatagramPacket packet = novel DatagramPacket(buf, buf.length);                     socket.receive(packet);     //this code block the plan catamenia                      // ship the reply to the customer at "address" too "port"                     InetAddress address = packet.getAddress();                     int port = packet.getPort();                      updatePrompt("Request from: " + address + ":" + port + "\n");                      String dString = novel Date().toString() + "\n"                             + "Your address " + address.toString() + ":" + String.valueOf(port);                     buf = dString.getBytes();                     packet = novel DatagramPacket(buf, buf.length, address, port);                     socket.send(packet);                  }                  Log.e(TAG, "UDP Server ended");              } choose conduct maintain of (SocketException e) {                 e.printStackTrace();             } choose conduct maintain of (IOException e) {                 e.printStackTrace();             } finally {                 if(socket != null){                     socket.close();                     Log.e(TAG, "socket.close()");                 }             }         }     }      somebody String getIpAddress() {         String ip = "";         travail {             Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface                     .getNetworkInterfaces();             acre (enumNetworkInterfaces.hasMoreElements()) {                 NetworkInterface networkInterface = enumNetworkInterfaces                         .nextElement();                 Enumeration<InetAddress> enumInetAddress = networkInterface                         .getInetAddresses();                 acre (enumInetAddress.hasMoreElements()) {                     InetAddress inetAddress = enumInetAddress.nextElement();                      if (inetAddress.isSiteLocalAddress()) {                         ip += "SiteLocalAddress: "                                 + inetAddress.getHostAddress() + "\n";                     }                  }              }          } choose conduct maintain of (SocketException e) {             // TODO Auto-generated choose conduct maintain of block             e.printStackTrace();             ip += "Something Wrong! " + e.toString() + "\n";         }          furnish ip;     } }  

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="16dp"     android:orientation="vertical"     tools:context="com.blogspot.android_er.androidudpserver.MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text="https://rootandroid.org//"         android:textStyle="bold" />      <TextView         android:id="@+id/infoip"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textStyle="italic" />      <TextView         android:id="@+id/infoport"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textStyle="italic" />      <TextView         android:id="@+id/state"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="un-initiated"         android:textSize="20dp"/>      <TextView         android:id="@+id/prompt"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:textSize="18dp"/> </LinearLayout>  

uses-permission of “android.permission.INTERNET” is needed inwards AndroidManifest.xml

Remark most life-cycle:
In this example, the DatagramSocket server is run inwards background thread. I haven’t grip the life-cycle rattling good (Actually I don’t intend whatever application volition convey UI similar this example). Consider the cases:

Case One:
– Start the app, the action display on covert too the DatagramSocket opened inwards associated thread.
– the code socket.receive(packet) block the plan flow, too then the thread rest hither too waiting information request.
– Exit the app. It volition develop running to false, to asking the thread to stop. But the thread is blocked in socket.receive(packet), too then it’s nonetheless running.
– Restart the app, the novel thread cannot opened upward the DatagramSocket, because it’s nonetheless held yesteryear one-time thread.
– Client ship a request, the DatagramSocket server reply the asking too leave of absence socket.receive(packet), too banking concern check running too exit.
– In this case, the electrical flow action too associated thread convey no DatagramSocket opened!

Case Two:
– Start the app, the action display on covert too the DatagramSocket opened inwards associated thread.
– the code socket.receive(packet) block the plan flow, too then the thread rest hither too waiting information request.
– Exit the app. It volition develop running to false, to asking the thread to stop. But the thread is blocked inwards socket.receive(packet), too then it’s nonetheless running.
– Client ship a request, the DatagramSocket server reply the asking too leave of absence socket.receive(packet), too banking concern check running too exit.
– Restart the app, too opened upward the DatagramSocket.
– In this case, the electrical flow action too associated thread tin opened upward DatagramSocket too function every bit expected.

  world cast MainActivity extends AppCompatActivity  Android Datagram/UDP Server exampleDownload the files .