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 :

Leave a Comment:

110 comments
mythili says August 20, 2011

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….

Reply
Rani says August 20, 2011

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..

Reply
mythili says August 20, 2011

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

Reply
Prajaktta says August 25, 2011

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?

Reply
Prajaktta says August 26, 2011

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?

Reply
Prajaktta says August 29, 2011

plz tell me how to do that…?plz

Reply
Rizwan says September 28, 2011

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..

Reply
Dave says October 27, 2011

Just wondering why you chose such a convoluted PrintWriter when

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

seems to do the trick…

Reply
Rajkanna says November 4, 2011

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.

Reply
Rajkanna says November 4, 2011

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.

Reply
murat says November 29, 2011

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

Reply
keifer says December 10, 2011

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?

Reply
LOL says December 20, 2011

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

Reply
phamliem says January 11, 2012

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

Thanks you !

Reply
phamliem says January 11, 2012

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

Thanks you !

Reply
phamliem says January 11, 2012

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

Thanks you !

Reply
Lucky says January 16, 2012

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

Reply
Android Tutorial | Android SDK Development & Programming | Zeeshan Akhter says January 27, 2012

[…] Socket Programming Posted by Sushant on August 17, 2011 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… Filed in: Android Development, Android Programming Tutorials 0 […]

Reply
vaickiballs says February 5, 2012

Very usefull and easy!
Thank you very much.

Reply
binil says February 8, 2012

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

Reply
Kingping says February 12, 2012

It Does not work :s

Reply
Wikus says February 12, 2012

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

Reply
Harald Ellingsen says February 13, 2012

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?

Reply
Harald Ellingsen says February 13, 2012

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?

Reply
Nauman says February 16, 2012

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

Reply
Saqib says February 26, 2012

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

Reply
Saqib says February 26, 2012

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

Reply
Nikhil says February 28, 2012

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

Reply
chandini says March 2, 2012

how to get the desktop server

Reply
chandini says March 2, 2012

want server on desktop

Reply
chandra says April 2, 2012

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

Reply
Sameer says April 12, 2012

Nice article…

Reply
Izak says April 15, 2012

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

Reply
Izak says April 15, 2012

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

Reply
mariano says April 26, 2012

protected static final int MSG_ID = 0×1337;

Error is not int ?!

Reply
liendlu says April 29, 2012

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!

Reply
shubham says May 3, 2012

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.

Reply
immy says May 17, 2012

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

Reply
immy says May 17, 2012

protected static final int MSG_ID = 0×1337;

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

Reply
Vidya says May 19, 2012

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

Reply
Vidya says May 19, 2012

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

Reply
soin says May 28, 2012

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

Reply
soin says May 28, 2012

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

Reply
soin says May 28, 2012

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

Reply
Neeti says May 30, 2012

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

Reply
Neeti says May 31, 2012

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.

Reply
bash says June 4, 2012

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?

Reply
can says June 24, 2012

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?

Reply
can says June 24, 2012

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?

Reply
triana says July 3, 2012

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 ? 🙁

Reply
zahoor says July 18, 2012

very good

Reply
srk says July 27, 2012

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

Reply
rahul says July 29, 2012

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

Reply
Maxa says July 31, 2012

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

Reply
Danymega898 says August 6, 2012

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

Reply
ira says August 12, 2012

It doesn’t work. The client crushes…

Reply
asaf says August 27, 2012

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

Reply
    Vahe says September 4, 2012

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

    Reply
Melos Hasanaj says September 2, 2012

yes there’s a problem with client

Reply
joy says September 28, 2012

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

Reply
Sajad Vafa says October 7, 2012

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.

Reply
manu says October 11, 2012

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.

Reply
manu says October 11, 2012

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.

Reply
Grace says October 16, 2012

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…

Reply
Rahul says October 18, 2012

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 !!

Reply
LK says October 18, 2012

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 ?

Reply
PS says October 19, 2012

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

Reply
kanika says November 7, 2012

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.

Reply
kanika says November 7, 2012

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.

Reply
kshitij says December 3, 2012

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.

Reply
mirandpp says December 6, 2012

anyone of you can upload the project?

Reply
Sara says December 13, 2012

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?

Reply
bhoomi says December 18, 2012

does it works i same pc itself??

Reply
bhoomi says December 18, 2012

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

Reply
Mai says December 26, 2012

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.

Reply
Bgouda says December 31, 2012

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

Reply
Ed.. says January 3, 2013

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

Reply
Gary says January 9, 2013

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?

Reply
gani says February 28, 2013

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

manu didi u got the error resolved?

Reply
amith says March 29, 2013

Thanks a lottt . . it works perfectly . .

Reply
Ramachandran says April 19, 2013

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

Reply
Santosh Rai says April 25, 2013

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

Reply
Santosh Rai says April 25, 2013

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

Reply
Mobile Phone says April 25, 2013

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.

Reply
iPhone says April 25, 2013

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!

Reply
saneeb says April 26, 2013

It crashes the application

Reply
vamsi says April 27, 2013

How to download this source code

Reply
harika says May 29, 2013

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

Reply
Hariram says May 31, 2013

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

Reply
rulfik says June 5, 2013

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!

Reply
sreekanth says June 6, 2013

pls help me i got socket exception unrechable network

Reply
sreekanth says June 6, 2013

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

Reply
kranti says June 20, 2013

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.

Reply
anirudh says June 26, 2013

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

Reply
anirudh says June 26, 2013

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

Reply
reeha says July 17, 2013

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

Reply
reeha says July 17, 2013

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

Reply
Andrea says July 22, 2013

you have to use AsyncTask to run the client thread

Reply
reeha says July 23, 2013

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

Reply
hello says July 30, 2013

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!!

Reply
reeha says July 31, 2013

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

Reply
covith says August 26, 2013

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.

Reply
vijaya says September 12, 2013

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.

Reply
Priyanka says September 27, 2013

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

Reply
Ari says October 3, 2013

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?

Reply
Ari says October 4, 2013

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

Reply
mario says October 8, 2013

there’s a problem with client

Reply
Android server request listener | Yasui Answers says December 10, 2014

[…] can use sockets for it. See here and […]

Reply
eisha says December 30, 2014

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

Reply
md hussain says February 25, 2015

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….

Reply
Add Your Reply