Socket Programming

19

This is a sample program that uses socket class to make a chat application, by this you can create a Server and a Client in two Emulator and chat to write and read data.

Underlying Algorithm:

Basic description of algorithm in step by step form:
1.) Create Two Projects one for server MyServer and another for client ServerClient.
2.) Put the following code snippet in res folder of MyServer project res/layout/main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
/>
<TextView android:text="TextView" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content">
</TextView>
</LinearLayout>

3.) Put the following code snippet in res folder of ServerClient project res/layout/main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:id="@+id/myTextView"
/>
<EditText android:text="EditText" android:layout_width="fill_parent" android:id="@+id/EditText01" android:layout_height="wrap_content">
</EditText>
<Button android:text="Button" android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content">
</Button>
</LinearLayout>

4.) Add the following permissions in AndroidManifest.xml of both project :

<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>

5.) Redirect the port :

i) run -> cmd -> telnet localhost 5554
ii) redir add tcp:5000:6000

6.) Run the both applications.

Steps to Create Server:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. MyServer. Enter following information:
Project name: MyServer
Build Target: Android APIs 2.1
Application name: MyServer
Package name: com.app. MyServer
Create Activity: MyServer

On Clicking Finish MyServer code structure is generated with the necessary Android Packages being imported along with MyServer.java. MyServer class will look like following:

package com.app.MyServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MyServer extends Activity {
   ServerSocket ss = null;
   String mClientMsg = "";
   Thread myCommsThread = null;
   protected static final int MSG_ID = 0x1337;
   public static final int SERVERPORT = 6000;

   @Override
   public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
	TextView tv = (TextView) findViewById(R.id.TextView01);
	tv.setText("Nothing from client yet");
	this.myCommsThread = new Thread(new CommsThread());
	this.myCommsThread.start();
   }

   @Override
   protected void onStop() {
	super.onStop();
	try {
		// make sure you close the socket upon exiting
		ss.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
   }

   Handler myUpdateHandler = new Handler() {
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_ID:
			TextView tv = (TextView) findViewById(R.id.TextView01);
			tv.setText(mClientMsg);
			break;
		default:
			break;
		}
		super.handleMessage(msg);
	}
   };
   class CommsThread implements Runnable {
	public void run() {
		Socket s = null;
		try {
			ss = new ServerSocket(SERVERPORT );
		} catch (IOException e) {
			e.printStackTrace();
		}
		while (!Thread.currentThread().isInterrupted()) {
			Message m = new Message();
			m.what = MSG_ID;
			try {
				if (s == null)
					s = ss.accept();
				BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
				String st = null;
				st = input.readLine();
				mClientMsg = st;
				myUpdateHandler.sendMessage(m);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
    }
}

Steps to Create Client:

2.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. ServerClient. Enter following information:
Project name: ServerClient
Build Target: Android APIs 2.1
Application name: ServerClient
Package name: com.app.ServerClient
Create Activity: ServerClient

On Clicking Finish ServerClient code structure is generated with the necessary Android Packages being imported along with ServerClient.java. ServerClient class will look like following:

package com.app.ServerClient;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;

public class SocketClient extends Activity {
   private Button bt;
   private TextView tv;
   private Socket socket;
   private String serverIpAddress = "10.0.2.2";
   // AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
   // PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
   // PORT 6000
   private static final int REDIRECTED_SERVERPORT = 5000;
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      bt = (Button) findViewById(R.id.myButton);
      tv = (TextView) findViewById(R.id.myTextView);
      try {
         InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
         socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
      } catch (UnknownHostException e1) {
         e1.printStackTrace();
      } catch (IOException e1) {
         e1.printStackTrace();
      }
      bt.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            try {
               EditText et = (EditText) findViewById(R.id.EditText01);
               String str = et.getText().toString();
               PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
               out.println(str);
               Log.d("Client", "Client sent message");
            } catch (UnknownHostException e) {
               tv.setText("Error1");
               e.printStackTrace();
            } catch (IOException e) {
               tv.setText("Error2");
               e.printStackTrace();
            } catch (Exception e) {
               tv.setText("Error3");
               e.printStackTrace();
            }
         }
      });
   }
}

Output –The final output:
Client :

Server :

  • chandra

    Hi,
    how to send images or photos using the above programming method.
    Thanks in advance.

  • Izak

    Finally i found a chat android code that is work, thanks alot, great effort
    Just in in the \"ServerClient.java\" code there was small mistake in the name of the activity:
    it was \"public class SocketClient extends Activity\" and the correct one is:
    \"public class ServerClient extends Activity\"
    Thanks again

  • mariano

    protected static final int MSG_ID = 0×1337;

    Error is not int ?!

  • srk

    Hi!
    Thnx your code helped me a lot and as per me the best code and explanation available on net…….thnx

  • Danymega898

    como puedo hacer un socket pero este tiene varias clases, como lo puedo integrar?

  • ira

    It doesn’t work. The client crushes…

  • asaf

    question : i have used ur example and this working fine on 2 emulators but on really phones its not working i got my phone ip and i tryed to connect to it from other phone but i got no respons + the ip u get is a local ip 10.X.X.X and there is no way to fowrd the port to ur target phone so i dont see how this can be done unless ur on the same network like wifi (i all so think the providers block it )or mabye am worng and there is a way??:)

  • Melos Hasanaj

    yes there’s a problem with client

  • Vahe

    How can you run 2 emulator, when I run I havent’recieved data on server, why?

  • joy

    i unable to connect the emulators using this code.. plz help me to do this

  • Sajad Vafa

    This works fine on emulator but when I try to use my phone as client and emulator as server it doesn’t work.
    I tried changing the ip address of server to 192.168.1.7 (my pc ip in wifi) but it didn’t work too.

  • manu

    It takes time to show the textview and edittext in client side and by clicking the button after entering the in edittext it is showing error3 in the textview.

  • manu

    It takes time to show the textview and edittext in client side and by clicking the button after entering the text in edittext it is showing error3 in the textview.

  • Grace

    I’m looking to do this but alot of the tutorials I’ve seen for Android warn against using Threads, they say instead to use AsyncTask and use the callback that comes with it… I’m not sure if you have thoughts on that but I’d love to know them as I’m trying to become more familiar in this area…

  • Rahul

    5.) Redirect the port :
    i) run -> cmd -> telnet localhost 5554
    ii) redir add tcp:5000:6000
    6.) Run the both applications
    What is this pls Explain !!

  • LK

    If it crashes, you may need to add this in the onCreate function

    StrictMode.ThreadPolicy policy = new StrictMode
    .ThreadPolicy
    .Builder()
    .permitNetwork()
    .build();

    StrictMode.setThreadPolicy(policy);

    After putting that, my program does not crash, but it get’s stuck when creating the socket. Any help ?

  • PS

    Is it possible to initialize socket connection between a mobile device and digital video recorder which is a server?

  • kanika

    It takes considerably long time to show the textview and edittext in client side and by clicking the button after entering the text in edittext it is showing error3 in the textview which when i explored is nullpointer exception, reason i’m unable to identify. the code didn’t go further after line no. 35 in client side. please do guide.

  • kanika

    It takes considerably long time to show the textview and edittext in client side and by clicking the button after entering the text in edittext it is showing error3 in the textview which when i explored is nullpointer exception, reason i’m unable to identify. the code didn’t go further after line no. 46 in client side. please do guide.

Proudly designed by Theme Junkie.