Tuesday, November 15, 2016

Socket Programming in Android - Client Server Communication

Dear All

As you know socket plays an important role in the client server communication.

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening.

In my example i had created two Apps. 
1. ServerSocket
2. ClientSocket
ServerSocket has
a. Layout
b. An interface 
c. MyServer.java class
d. MainActivity

The codes are in sequence is as 
 a. Layout
<TextView

    android:layout_width="wrap_content"

    android:layout_height="40dp"

    android:text="Client Message "

    android:id="@+id/textClient" />

<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Start Server"

    android:id="@+id/button"

    android:onClick="connect"

   />
b. An interface 
package com.exam.ravi.serversocket;

public interface DataDisplay {
    void Display(String messgae);
}


c. MyServer.java class
package com.exam.ravi.serversocket;

import android.os.Handler;
import android.os.Message;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
    Thread m_objThread;
    ServerSocket m_server;
    DataDisplay m_dataDisplay;

    public MyServer() { }
    public void setEventListener(DataDisplay dataDisplay)
    {
        m_dataDisplay = dataDisplay;
    }
    public void startListening()
    {
        m_objThread = new Thread(new Runnable() {
            @Override            public void run() {
                try                {
                    m_server = new ServerSocket(2001);
                    Socket connectedSocket = m_server.accept();
                    Message clientMessage = Message.obtain();
                    ObjectInputStream ois = new 
                         ObjectInputStream(connectedSocket.getInputStream());
                    String strMessage = (String) ois.readObject();
                    clientMessage.obj = strMessage;
                    mHandler.sendMessage(clientMessage);
                    ObjectOutputStream oos = new 
                           ObjectOutputStream(connectedSocket.getOutputStream());
                    oos.writeObject("Hi Client....");
                    ois.close();
                    oos.close();
                    m_server.close();
                }
                catch (Exception e)
                {

                    e.printStackTrace();
                }
            }
        });
        m_objThread.start();
    }
    Handler mHandler = new Handler()
    {
        @Override        public void handleMessage(Message msg) {
            m_dataDisplay.Display(msg.obj.toString());
        }
    };

}

d. MainActivity
package com.exam.ravi.serversocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements DataDisplay{
    TextView serverMessage;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serverMessage = (TextView) findViewById(R.id.textClient);


    }
    public void connect(View view)
    {
        MyServer server = new MyServer();
        server.setEventListener(this);
        server.startListening();
    }
    public void Display(String message)
    {
        serverMessage.setText(" " +message);
    }
}

ClientSocket has
a. Layout
b. MainActivity
a. Layout is as 
<TextView

    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:text="Server message"
    android:id="@+id/txtser" />

<Button    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Client "
    android:id="@+id/btnclk"
    android:onClick="start"
     />
b. MainActivity is as 
package com.exam.ravi.clientsocket;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
    TextView sermsg;
    Thread mobjThreadClient;
    Socket clientSocket;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sermsg = (TextView) findViewById(R.id.txtser);

    }
    public void start(View view)
    {
        mobjThreadClient = new Thread(new Runnable() {
            @Override            public void run() {
                try                {
                    clientSocket = new Socket("127.0.0.1",2001);
                    ObjectOutputStream oos = new 
                              ObjectOutputStream(clientSocket.getOutputStream());
                    oos.writeObject("Hellow Server... ");
                    Message serverMessage = Message.obtain();
                    ObjectInputStream ois = new 
                          ObjectInputStream(clientSocket.getInputStream());
                    String strmsg= (String ) ois.readObject();
                    serverMessage.obj=strmsg;
                    mHandler.sendMessage(serverMessage);
                    oos.close();
                    ois.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
        mobjThreadClient.start();
    }
    Handler mHandler = new Handler()
    {
        @Override        public void handleMessage(Message msg) {
            messageDisplay(msg.obj.toString());
        }
    };
    public void messageDisplay(String str)
    {
        sermsg.setText(" "+ str);
    }
}

Don't forget to add permission in both App
<uses-permission android:name="android.permission.INTERNET"/>

Output Will be Like 




No comments:

Post a Comment