Thursday 20 March 2014

Java Socket Server-Client Example

First create a new Java Project in Android Eclipse

then Create   a Class Name 1)    SocketServerExample.java

Code For this class.........................



public class SocketServerExample {
    //static ServerSocket variable
    private static ServerSocket server;
    //socket server port on which it will listen
    private static int port = 9876;
    
    public static void main(String args[]) throws IOException, ClassNotFoundException{
        //create the socket server object
        server = new ServerSocket(port);
        //keep listens indefinitely until receives 'exit' call or program terminates
        while(true){
            System.out.println("Waiting for client request");
            //creating socket and waiting for client connection
            Socket socket = server.accept();
            //read from socket to ObjectInputStream object
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            //convert ObjectInputStream object to String
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);
            //create ObjectOutputStream object
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //write object to Socket
            oos.writeObject("Hi Client "+message);
            //close resources
            ois.close();
            oos.close();
            socket.close();
            //terminate the server if client sends exit request
            if(message.equalsIgnoreCase("exit")) break;
        }
        System.out.println("Shutting down Socket server!!");
        //close the ServerSocket object
        server.close();
    }
    




And Create a Client Class

2)SocketClientExample.java



public class SocketClientExample {
     public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
            //get the localhost IP address, if server is running on some other IP, you need to use that
            InetAddress host = InetAddress.getLocalHost();
            Socket socket = null;
            ObjectOutputStream oos = null;
            ObjectInputStream ois = null;
            for(int i=0; i<5;i++){
                //establish socket connection to server
                socket = new Socket(host.getHostName(), 9876);
                //write to socket using ObjectOutputStream
                oos = new ObjectOutputStream(socket.getOutputStream());
                System.out.println("Sending request to Socket Server");
                if(i==4)oos.writeObject("exit");
                else oos.writeObject(""+i);
                //read the server response message
                ois = new ObjectInputStream(socket.getInputStream());
                String message = (String) ois.readObject();
                System.out.println("Message: " + message);
                //close resources
                ois.close();
                oos.close();
                Thread.sleep(100);
            }
        }




Then first  run the Server class after run client class.

the out put will be in Java console..............................




Sending request to Socket Server
Message: Hi Client 0
Sending request to Socket Server
Message: Hi Client 1
Sending request to Socket Server
Message: Hi Client 2
Sending request to Socket Server
Message: Hi Client 3
Sending request to Socket Server
Message: Hi Client exit
 

Wednesday 12 March 2014

Learn The NDK,Compile JNI (Java Native Interface) using android NDK (Native Development kit)

It is boring to know things without visualization as we think, pictures comes in our mind so let’s experience it with an example and create an image in your mind. Before we go I assume you have done all setup for Android and have knowledge of Android SDK.

Step 1: First create a project then create a folder named jni in your project directory.
Figure: 1

Step 2: Create addition.c file in jni folder and add the below lines.
#include "com_ndkadd_Addition_Addition.h"
#include <jni.h>
jint Java_com_ndkadd_Addition_Addition_mAdd(JNIEnv * env, jobject jObj, jint value1, jint value2) { return (value1 + value2);}

Step 3: Create Android.mk file in jni folder and add the below code
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := Addition
LOCAL_SRC_FILES := addition.c
include $(BUILD_SHARED_LIBRARY)


Step 4: Below the code for your activity and usage of created .so file in your libs folder.
public class Addition extends Activity {
static
{
System.loadLibrary("Addition");
}
public native int mAdd(int v1,int v2);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tAdd= new TextView(this);
tAdd.setText(""+mAdd(5,5));
setContentView(tAdd);
}
}


Step 5: Now we need to generate header files so make sure you have java installed and all environment variables set. Navigate to classes folder under bin folder of your project directory (in my case it’s “D:\WorkSpace\Addition\bin\classes”) from command prompt and execute the following command.
javah -jni com.ndkadd.Addition.Addition
(*”com.ndkadd.Addition” is my package name so replace it with your’s and “Addition” is my class name)

Step 6: Above command results in a com_ndkadd_Addition_Addition.h file under classes folder of your project directory so copy the created com_ndkadd_Addition_Addition.h file to jni folder of your project in eclipse.

Step 7: Now set environment variable for NDK as shown in figure below:-