Saturday, 24 October 2015

Android server socket example | connect multiple clients to the server using server socket connection

The server socket helps you to connect the clients with server. In this tutorial we are going to build a message delivering application in android using server socket in which you could connect multiple clients(android devices) to the server(PC).
android server socket example


Steps:
1. Create a java project and add the following classes

server.java
 import java.io.IOException;  
 import java.net.ServerSocket;  
 import java.net.Socket;  
 public class Server {  
 public static void main(String args[]){  
   Socket s=null;  
   ServerSocket ss2=null;  
   System.out.println("Server Listening......");  
   try{  
     ss2 = new ServerSocket(4444); // can also use static final PORT_NUM , when defined  
   }  
   catch(IOException e){  
   e.printStackTrace();  
   System.out.println("Server error");  
   }  
   while(true){  
     try{  
       s= ss2.accept();  
       System.out.println("connection Established");  
       Reciever st=new Reciever(s);  
       st.start();  
     }  
   catch(Exception e){  
     e.printStackTrace();  
     System.out.println("Connection Error");  
   }  
   }  
 }  
 }//class ends  

Sender.java
import java.io.IOException;  
 import java.io.PrintWriter;  
 import java.net.Socket;  
 public class Sender {  
   private PrintWriter out;  
   public Sender(Socket clientSocket) {  
     try {  
       out = new PrintWriter(clientSocket.getOutputStream(), true);  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
   }  
   public void sendMessage(String message) {  
        out.println(message); // Print the message on output stream.  
     out.flush();  
     message="";  
        System.out.println("Server: " + message + "\n"); // Print the message on chat window.  
   }  
 }  

Receiver.java
import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.io.PrintWriter;  
 import java.net.Socket;  
 class Reciever extends Thread{   
   String line=null;  
   BufferedReader is = null;  
   PrintWriter os=null;  
   Socket s=null;  
   public Reciever(Socket s){  
     this.s=s;  
   }  
   public void run() {  
   try{  
     is= new BufferedReader(new InputStreamReader(s.getInputStream()));  
     os=new PrintWriter(s.getOutputStream());  
   }catch(IOException e){  
     System.out.println("IO error in server thread");  
   }  
   try {  
     line=is.readLine();  
     while(line.compareTo("QUIT")!=0){  
       os.println(line);  
       os.flush();  
       if(line.equals("syncDb")){  
            DataHandler a = new DataHandler();  
            a.syncDb(s);  
            break;  
       }  
       else{  
       //  
       System.out.println("Response to Client : "+line);  
       line=is.readLine();  
       }  
     }    
   } catch (IOException e) {  
     line=this.getName(); //reused String line for getting thread name  
     System.out.println("IO Error/ Client "+line+" terminated abruptly");  
   }  
   catch(NullPointerException e){  
     line=this.getName(); //reused String line for getting thread name  
     System.out.println("Client "+line+" Closed");  
   }  
   finally{    
   try{  
     System.out.println("Connection Closing..");  
     if (is!=null){  
       is.close();   
       System.out.println(" Socket Input Stream Closed");  
     }  
     if(os!=null){  
       os.close();  
       System.out.println("Socket Out Closed");  
     }  
     if (s!=null){  
     s.close();  
     System.out.println("Socket Closed");  
     }  
     }  
   catch(IOException ie){  
     System.out.println("Socket Close Error");  
   }  
   }//end finally  
   }  
 }  

DataHandler.Java
import java.net.Socket;  
 public class DataHandler {  
      public static void syncDb(Socket s) {  
           Sender sender = new Sender(s);  
           sender.sendMessage("***start***");  
           sender.sendMessage("This is a message from the server");  
           sender.sendMessage("***stop***");  
      }  
 }  

That's all for the server-side.

2.Copy and paste the below code to your android activity class.
import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.io.PrintWriter;  
 import java.net.Socket;  
 import java.net.UnknownHostException;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.os.AsyncTask;  
 import android.os.Build;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Toast;  
 public class MainActivity extends Activity {  
      private Socket client;  
      private PrintWriter printwriter;  
      private BufferedReader bufferedReader;  
      private ProgressDialog pDialog;  
      String host;  
      int port;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
      }  
      /**  
       * This AsyncTask create the connection with the server and initialize the  
       * chat senders and receivers.  
       */  
      private class ChatOperator extends AsyncTask<Void, Void, Void> {  
           @Override  
           protected Void doInBackground(Void... arg0) {  
                try {  
                     client = new Socket(host, port); // Creating the  
                                                                            // server socket.  
                     if (client != null) {  
                          printwriter = new PrintWriter(client.getOutputStream(),  
                                    true);  
                          InputStreamReader inputStreamReader = new InputStreamReader(  
                                    client.getInputStream());  
                          bufferedReader = new BufferedReader(inputStreamReader);  
                     } else {  
                          System.out  
                                    .println("Server has not bean started on port 4444.");  
                     }  
                } catch (UnknownHostException e) {  
                     System.out.println("Faild to connect server " + host);  
                     e.printStackTrace();  
                } catch (IOException e) {  
                     System.out.println("Faild to connect server " + host);  
                     e.printStackTrace();  
                }  
                return null;  
           }  
           /**  
            * Following method is executed at the end of doInBackground method.  
            */  
           @Override  
           protected void onPostExecute(Void result) {  
                final Sender messageSender = new Sender(); // Initialize chat sender  
                // AsyncTask.  
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {  
                     messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);  
                } else {  
                     messageSender.execute();  
                }  
                Receiver receiver = new Receiver(); // Initialize chat receiver  
                                                             // AsyncTask.  
                receiver.execute();  
           }  
      }  
      /**  
       * This AsyncTask continuously reads the input buffer and show the chat  
       * message if a message is availble.  
       */  
      private class Receiver extends AsyncTask<Void, Void, Void> {  
           private String message;  
           @Override  
           protected Void doInBackground(Void... params) {  
                while (true) {  
                     try {  
                          if (bufferedReader.ready()) {  
                               message = bufferedReader.readLine();  
                               publishProgress(null);  
                          }  
                     } catch (UnknownHostException e) {  
                          e.printStackTrace();  
                     } catch (IOException e) {  
                          e.printStackTrace();  
                     }  
                     try {  
                          Thread.sleep(100);  
                     } catch (InterruptedException ie) {  
                     }  
                }  
           }  
           @Override  
           protected void onProgressUpdate(Void... values) {  
                try {  
                     Toast.makeText(getApplicationContext(),  
                               "Received message: "+message, Toast.LENGTH_LONG).show();  
                } catch (Exception e) {  
                     // TODO: handle exception  
                }  
           }  
      }  
      /**  
       * This AsyncTask sends the chat message through the output stream.  
       */  
      private class Sender extends AsyncTask<Void, Void, Void> {  
           @Override  
           protected Void doInBackground(Void... params) {  
                printwriter.write("message from client" + "\n");  
                printwriter.flush();  
                Log.d("message", "send");  
                return null;  
           }  
           @Override  
           protected void onPostExecute(Void result) {  
           }  
      }  
      public void LoadAndSave(View v) {  
           pDialog = new ProgressDialog(MainActivity.this);  
           pDialog.setMessage("Loading meassage. Please wait...");  
           pDialog.setIndeterminate(false);  
           pDialog.setCancelable(false);  
           pDialog.show();  
           ChatOperator chatOperator = new ChatOperator();  
           chatOperator.execute();  
      }  
 }// activity ends  

3. Copy and paste the below xml to you layout xml file.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   >  
   <TableLayout  
     android:layout_width="fill_parent"  
     android:layout_height="172dp"  
     android:stretchColumns="1" >  
     <Button  
       android:id="@+id/button1"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:layout_marginBottom="20dp"  
       android:layout_marginTop="20dp"  
       android:onClick="LoadAndSave"  
       android:text="send a message to server" />  
   </TableLayout>  
 </ScrollView>  

4.Finally add internet permission to your android manifest.
<uses-permission android:name="android.permission.INTERNET" >

Now run the server and connect as much as client!



No comments:

Post a Comment