Socket Programming

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"?-->
    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"
/>

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

<!--?xml version="1.0" encoding="utf-8"?-->
    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"
/>

<button>
</button>

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


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 :

About the Author

Leave a Reply 110 comments

mythili - August 20, 2011 Reply

Hi,
will this example works in two emulators of different machines.i have two machines like 192.168.0.10 and 192.168.0.25,can i run server in one machine and client in other machine.will socket connection works like that?if not can you just give an example for that?

kindly help as i am new to android….

Rani - August 20, 2011 Reply

Hi,
will it be possible to run this example in two different machines like server in one machine and client in another machine.If not please specify such example as i am using Walkie talkie in android..
kindly help as i am new to android..

mythili - August 20, 2011 Reply

I tried to run this example but in both emulators it saying as application cannot run the process(force close).please let me know solution for this problem

Prajaktta - August 25, 2011 Reply

hi shushant;
i tried all the steps given, but i couldnt understand the step 5.. will you plz explain me in detail…
rather i tried different way…open 2 different avd & i want to run sever on one avd & client on other avd[is it possible?]…but i couldnt understand that how to change avd while running next project on different avd ;when already one project is running on one avd…will you plz tell me how to do this?

Prajaktta - August 26, 2011 Reply

hi shushant;
i tried all the steps given, but i couldnt understand the step 5.. will you plz explain me in detail…
rather i tried different way…open 2 different avd & i want to run sever on one avd & client on other avd[is it possible?]…but i couldnt understand that how to change avd while running next project on different avd ;when already one project is running on one avd…will you plz tell me how to do this?

Prajaktta - August 29, 2011 Reply

plz tell me how to do that…?plz

Rizwan - September 28, 2011 Reply

Hi Sushant,

Thanks for the code for socket programming.. i tried in the same way u have mentioned, except for changing the IP address(in my system it is 10.0.2.15).. but when i execute the code & send a message from client – I’m getting “Error 3″ in client side android window.
Please do suggest me to how to get over this error..

Dave - October 27, 2011 Reply

Just wondering why you chose such a convoluted PrintWriter when

out = new PrintWriter(sock.getOutputStream(), true);

seems to do the trick…

Rajkanna - November 4, 2011 Reply

hi sushant,

I done what you said above, but i am getting the error “error3″.

When i have to do the following steps?

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

what is the need of the above step? and i do it to connect to serverclient or myserver emulator?

Thanks in advance.

Rajkanna - November 4, 2011 Reply

hi sushant,

I done what you said above, but i am getting the error "error3".

When i have to do the following steps?

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

what is the need of the above step? and i do it to connect to serverclient or myserver emulator?

Thanks in advance.

murat - November 29, 2011 Reply

hi :)
first of all its a good article:)
I working on android with socket programming I try your code and ı run cmd and ı opened ports successfully but still ı taking error3 exception
Do u have any opinion for that?
thnk u

keifer - December 10, 2011 Reply

hi, i get this error when i follow the steps given, using ‘ant debug’ in linux,

/home/keifer/Desktop/android_sdk/android-sdk-linux/tools/ant/build.xml:421: org.xml.sax.SAXParseException; lineNumber: 17; columnNumber: 2; The markup in the document following the root element must be well-formed.

As I’m new to all of this field, wanted to try such application. Can you please guide me?

LOL - December 20, 2011 Reply

client cannot send the msg.
it appears error3 in ServerClient.
anyone?

phamliem - January 11, 2012 Reply

Thanks Sushant for this Tutorial. Great!!!
Can you add “function Client receive data from Server”. ???

Thanks you !

phamliem - January 11, 2012 Reply

Thanks Sushant for this Tutorial. Great!!!
Can you add "function Client receive data from Server". ???

Thanks you !

phamliem - January 11, 2012 Reply

Thanks Sushant for this Tutorial. Great!!!
Can you add \&quot;function Client receive data from Server\&quot;. ???

Thanks you !

Lucky - January 16, 2012 Reply

It is not working…there is no error but message is not sending to the server emulator..please help

vaickiballs - February 5, 2012 Reply

Very usefull and easy!
Thank you very much.

binil - February 8, 2012 Reply

hi im using android 2.3.3 .. and this code is crashing.. is there a working code for 2.3.3

Kingping - February 12, 2012 Reply

It Does not work :s

Wikus - February 12, 2012 Reply

Hi, I used this example to do some research on the topic of socket programming. However I found that the client side constantly give Error3. So i changed it so it shows the error code (java.lang.NullPointerException).

Please help.
Wikus

Harald Ellingsen - February 13, 2012 Reply

Hey,

i’m writing a client / server app that uses sockets and I’m currently using AsyncTask for threads to update my UI thread.

My clientphone will send two separate control signals (motor and steering) to the serverphone which displays this information on the UI thread.

When do I use AsyncTask and when do I use a Thread class and Handlers to get the updates to the UI?

Benefits drawbacks?

Harald Ellingsen - February 13, 2012 Reply

Hey,

i’m writing a client / server app that uses sockets and I’m currently using AsyncTask for threads to update my UI thread.

My clientphone will send two separate control signals (motor and steering) to the serverphone which displays this information on the UI thread.

When do I use AsyncTask and when do I use a Thread class and Handlers to get the updates to the UI?

Benefits drawbacks?

Nauman - February 16, 2012 Reply

Hi
can i transfer image using this method because the size of image is must larger. Does size matter?

Saqib - February 26, 2012 Reply

hi, nice tutorial… but i have an issue when I run on my 2 emulators with exactly what you explained.. i get nothing being transferred between both… both are running fine but not working…i am using that at house without any firewall or proxy thing… will you please help me out?
thanks in advance

Saqib - February 26, 2012 Reply

Thanks man, i just tried it once more and it worked… you saved my day!

Nikhil - February 28, 2012 Reply

I have tried this code but its not working …
I have error 3 on client side on to the emulator
plz help me

chandini - March 2, 2012 Reply

how to get the desktop server

chandini - March 2, 2012 Reply

want server on desktop

chandra - April 2, 2012 Reply

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

Sameer - April 12, 2012 Reply

Nice article…

Izak - April 15, 2012 Reply

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

Izak - April 15, 2012 Reply

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 - April 26, 2012 Reply

protected static final int MSG_ID = 0×1337;

Error is not int ?!

liendlu - April 29, 2012 Reply

Hi!
Ask yourself why to use address 10.0.2.2, for example, to run on 2 computers connected to Finland, then how to use ip.
Vietnam so his English was not good, because you just help.
Thanks in advance!

shubham - May 3, 2012 Reply

Hi , I am also trying to similar kind of thing, in my case PC working as server , emulator as client ..but I am facing error , log as follow :

05-03 12:32:16.813: I/ActivityManager(77): Start proc com.test for activity com.test/.TestActivity: pid=964 uid=10041 gids={3003}
05-03 12:32:17.154: W/NetworkManagementSocketTagger(77): setKernelCountSet(10041, 1) failed with errno -2
05-03 12:32:18.064: W/System.err(964): java.net.ConnectException: failed to connect to /127.0.0.1 (port 11701): connect failed: ECONNREFUSED (Connection refused)
05-03 12:32:18.064: W/System.err(964): at libcore.io.IoBridge.connect(IoBridge.java:114)
05-03 12:32:18.074: W/System.err(964): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-03 12:32:18.074: W/System.err(964): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
05-03 12:32:18.084: W/System.err(964): at java.net.Socket.startupSocket(Socket.java:566)
05-03 12:32:18.084: W/System.err(964): at java.net.Socket.tryAllAddresses(Socket.java:127)
05-03 12:32:18.084: W/System.err(964): at java.net.Socket.(Socket.java:177)
05-03 12:32:18.084: W/System.err(964): at java.net.Socket.(Socket.java:149)
05-03 12:32:18.094: W/System.err(964): at com.azoi.neo.Connection.connect(Connection.java:28)
05-03 12:32:18.094: W/System.err(964): at com.azoi.neo.IClient.connect(IClient.java:11)
05-03 12:32:18.094: W/System.err(964): at com.test.TestActivity.connection(TestActivity.java:73)
05-03 12:32:18.094: W/System.err(964): at com.test.TestActivity.access$0(TestActivity.java:69)
05-03 12:32:18.104: W/System.err(964): at com.test.TestActivity$1.run(TestActivity.java:37)
05-03 12:32:18.104: W/System.err(964): at java.lang.Thread.run(Thread.java:856)
05-03 12:32:18.113: W/System.err(964): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
05-03 12:32:18.113: W/System.err(964): at libcore.io.Posix.connect(Native Method)
05-03 12:32:18.154: W/System.err(964): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
05-03 12:32:18.154: W/System.err(964): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-03 12:32:18.174: W/System.err(964): at libcore.io.IoBridge.connect(IoBridge.java:112)
05-03 12:32:18.174: W/System.err(964): … 12 more

please give suggestion if any one have idea over this.

immy - May 17, 2012 Reply

All code work but there z some error….

protected static final int MSG_ID = 0×1337;

so what to do…plz…any 1 help me…. brotherz

immy - May 17, 2012 Reply

protected static final int MSG_ID = 0×1337;

Error in this code… what to do…plz any 1 help me…..hurry up

Vidya - May 19, 2012 Reply

I tried using it on eclipse…
I typed at client side …whenever i click Button nothing happens…

Vidya - May 19, 2012 Reply

I tried using it on eclipse…
I typed at client side …whenever i click Button nothing happens…
And Server is idle..

soin - May 28, 2012 Reply

Hi,
my program has failed and showed “Error 3″ in ServerClient.
What can i do?
thks.

soin - May 28, 2012 Reply

Hi,
my program has failed and showed "Error 3" in ServerClient.
What can i do?
thks.

soin - May 28, 2012 Reply

Hi,
my program has failed and showed Error 3 in ServerClient.
What can i do?
thks.

Neeti - May 30, 2012 Reply

though no syntax error found, Its not working for me:'(

Neeti - May 31, 2012 Reply

Its Nice:) Thanks.. but can you post about how to add some more lines of code in this existing program so that the server can also send messages to client.

bash - June 4, 2012 Reply

Whenever I compile and run this program, and type anything in the server client, it gives me error3 . Also, should both activities be run on the same emulator or different ones?

can - June 24, 2012 Reply

hey; i try to run this code; ı didnt take a error but dont happend anythnig.. i give “error 3″ onthe textview.. can u help me?

can - June 24, 2012 Reply

hey; i try to run this code; ı didnt take a error but dont happend anythnig.. it give me ; error3 onthe textview.. can u help me?

triana - July 3, 2012 Reply

Hi there, I am trying your codes however I have stuck at the client side.It shows errors and the first error message shown was “thread exiting without uncaught exception.”
I truly do not know what went wrong ? :-(

zahoor - July 18, 2012 Reply

very good

srk - July 27, 2012 Reply

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

rahul - July 29, 2012 Reply

when i try to run this i get following error
07-29 12:35:29.387: W/System.err(336): java.lang.NullPointerException
07-29 12:35:29.387: W/System.err(336): at com.example.socketclient.SocketClient$1.onClick(SocketClient.java:60)
07-29 12:35:29.387: W/System.err(336): at android.view.View.performClick(View.java:2485)
07-29 12:35:29.387: W/System.err(336): at android.view.View$PerformClick.run(View.java:9080)
07-29 12:35:29.387: W/System.err(336): at android.os.Handler.handleCallback(Handler.java:587)
07-29 12:35:29.387: W/System.err(336): at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 12:35:29.397: W/System.err(336): at android.os.Looper.loop(Looper.java:123)
07-29 12:35:29.397: W/System.err(336): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-29 12:35:29.397: W/System.err(336): at java.lang.reflect.Method.invokeNative(Native Method)
07-29 12:36:12.067: W/System.err(336): at android.view.View.performClick(View.java:2485)
07-29 12:36:12.067: W/System.err(336): at android.view.View$PerformClick.run(View.java:9080)
07-29 12:36:12.067: W/System.err(336): at android.os.Handler.handleCallback(Handler.java:587)
07-29 12:36:12.067: W/System.err(336): at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 12:36:12.067: W/System.err(336): at android.os.Looper.loop(Looper.java:123)
07-29 12:36:12.067: W/System.err(336): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-29 12:36:12.077: W/System.err(336): at java.lang.reflect.Method.invokeNative(Native Method)
07-29 12:36:12.077: W/System.err(336): at java.lang.reflect.Method.invoke(Method.java:507)
07-29 12:36:12.077: W/System.err(336): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-29 12:36:12.077: W/System.err(336): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-29 12:36:12.077: W/System.err(336): at dalvik.system.NativeStart.main(Native Method)
07-29 12:36:50.327: D/SntpClient(60): request time failed: java.net.SocketException: Address family not supported by protocol

Maxa - July 31, 2012 Reply

Hi guys, nice tutorial , i want just say that don’t forget change the little × in ” int MSG_ID=0×1337;

Danymega898 - August 6, 2012 Reply

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

ira - August 12, 2012 Reply

It doesn’t work. The client crushes…

asaf - August 27, 2012 Reply

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??:)

    Vahe - September 4, 2012 Reply

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

Melos Hasanaj - September 2, 2012 Reply

yes there’s a problem with client

joy - September 28, 2012 Reply

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

Sajad Vafa - October 7, 2012 Reply

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 - October 11, 2012 Reply

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 - October 11, 2012 Reply

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 - October 16, 2012 Reply

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 - October 18, 2012 Reply

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 - October 18, 2012 Reply

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 - October 19, 2012 Reply

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

kanika - November 7, 2012 Reply

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 - November 7, 2012 Reply

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.

kshitij - December 3, 2012 Reply

Hello,
I am able to implement the code the problem I am facing here is that on the server side When I started the application It is showing the error

12-03 06:25:38.510: W/System.err(418): java.net.SocketException: Socket is closed

I dont know what is the possible bug. If you can help me It would be appreciable.
I more thing I am testing on two emulators.

mirandpp - December 6, 2012 Reply

anyone of you can upload the project?

Sara - December 13, 2012 Reply

When I run the server project, it runs fine. But when I run the client project, the emulator asks to force close the application. Please tell me why is it happening?

bhoomi - December 18, 2012 Reply

does it works i same pc itself??

bhoomi - December 18, 2012 Reply

does it works in same pc itself?? i mean to tell both server and client works in single pc.

Mai - December 26, 2012 Reply

I want to use a socket to control an android phone from another android phone. for example, if the server realizes an action, the client will realize this action, too. Please guide me! Thanks.

Bgouda - December 31, 2012 Reply

Create two emulator-5554 run MyServer and in emulator-5556 run ServerClient.

Ed.. - January 3, 2013 Reply

Do you have this project packaged? I couldn’t get it working. Would really appreciate a copy. Found your tutorial a refreshing example. Thanks

Gary - January 9, 2013 Reply

Hi,

I’m just wondering if you could use this to communicate between an emulator and a device?? Create the two activities in the one project, launch it on the emulator first, have your manifest set that you can have two buttons to select either or activity, select one on the emulator, then run it on the device, selecting the second activity?

gani - February 28, 2013 Reply

I also got the error3 when i press submit…
please help me….

manu didi u got the error resolved?

amith - March 29, 2013 Reply

Thanks a lottt . . it works perfectly . .

Ramachandran - April 19, 2013 Reply

i not understand 5th and 6th step . i do all things . but when i try to run . 1st i run the server and then i run the client in the same machine . when i type msg and click send it tell that

the application server client(process com.app.serverclient) has stoped un expectedly. can any one help for this

Santosh Rai - April 25, 2013 Reply

I have problem with my client class as exception throws plz help me

Santosh Rai - April 25, 2013 Reply

package com.example.clientservertest;
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 = “127.0.0.1”;
// 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.activity_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();
}
}
});
}
}
throw the exception

Mobile Phone - April 25, 2013 Reply

We’re a group of volunteers and starting a new scheme in our community. Your site offered us with helpful info to paintings on. You have done a formidable process and our entire community shall be thankful to you.

iPhone - April 25, 2013 Reply

Magnificent put up, very informative. I’m wondering why the other experts of this sector don’t notice this. You must proceed your writing. I’m confident, you have a great readers’ base already!

saneeb - April 26, 2013 Reply

It crashes the application

vamsi - April 27, 2013 Reply

How to download this source code

harika - May 29, 2013 Reply

when click button in client, I am getting error 3. what is that? how can get output?

Hariram - May 31, 2013 Reply

Hii,

Thanks for this effort. I am pretty new to socket program, I can able to run the app and the server can get the string from client. But this will happen for first time, when i post to server for second time, the edited text is not appear. I really dont know where i made mistake. Moreover i dint wrote separate class for server or client. I mingled together. Can you please guide me on where i made mistake or what should i do to post the message concurrently. Thanks in advance

rulfik - June 5, 2013 Reply

Hi! Could you send to my e-mail this project?
ServerClient application hangs.
ServerClient/srs/com/app/ServerClient/ServerClient.java
faulty code:
try {
          InetAddress serverAddr = InetAddress.getByName (serverIpAddress);
          socket = new Socket (serverAddr, REDIRECTED_SERVERPORT);
       } Catch (UnknownHostException e1) {
          e1.printStackTrace ();
       } Catch (IOException e1) {
          e1.printStackTrace ();
       }
Thank!

sreekanth - June 6, 2013 Reply

pls help me i got socket exception unrechable network

sreekanth - June 6, 2013 Reply

pls help me i got socket exception unrechable network
using same code server code in mobile and client in one mobile

kranti - June 20, 2013 Reply

it will work only when both server and client connected to same network or router.But if you connect server and client to different networks(routers) it is not working how can i do it.

anirudh - June 26, 2013 Reply

hey i am getting the exception(android.os.NetworkOnMainThreadException) on running ServerClient programm please help me.

anirudh - June 26, 2013 Reply

hey i am getting the exception(android.os.NetworkOnMainThreadException) on running ServerClient programm please help me.

reeha - July 17, 2013 Reply

hi,,
even i too get the same error like how kanika got….pls help….am trying this since 1 week….urgnt

reeha - July 17, 2013 Reply

hi,,
even i too get the same error like how kanika got….pls help….am trying this since 1 week….urgnt

Andrea - July 22, 2013 Reply

you have to use AsyncTask to run the client thread

reeha - July 23, 2013 Reply

hi,,
even i too get the same error like how kanika got….pls help….am trying this since 1 week….urgnt………provide proper information…….

hello - July 30, 2013 Reply

5.) Redirect the port :
i) run -> cmd -> telnet localhost 5554
ii) redir add tcp:5000:6000
6.) Run the both applications
does here any one that can explain how to do this!!

reeha - July 31, 2013 Reply

now i got as connected….but the client message does not get displayed in server emulator….the emulator is as it is…………pls help..

covith - August 26, 2013 Reply

I test it already, it done well. but i use it on the real phone its have no the result. so now could u share me the source code to chat on phone? many thanks.

vijaya - September 12, 2013 Reply

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.

Priyanka - September 27, 2013 Reply

How to get port number if my server is wifi . I am building app where i want to switch on or off lights by app by sending command to wifi

Ari - October 3, 2013 Reply

i have copied this code onto my project, i have changed the ip address with my system ip address still im unable to get any text in my server emulator

can anyone please point me out what am i doing wrong?

Ari - October 4, 2013 Reply

I’m getting this warning

W/InputEventReceiver(1167): Attempted to finish an input event but the input event receiver has already been disposed.

im checking in two emulators and the message is not send to the server emulator, i have done all that is necessary and mentioned here, what might i be missing??

mario - October 8, 2013 Reply

there’s a problem with client

eisha - December 30, 2014 Reply

hi… very informative post thanks.. i want to ask u that what if i want to maintain a database at server side and accept database values from client side???? if u have any idea share with me it will be a great help for me

md hussain - February 25, 2015 Reply

i have suceessfully send the msg on server but enable to receive server response from server if have you any idea please share it with me it will my great pleasure to me….

Leave a Reply: