Leave a Comment:
110 comments

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

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

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?


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

Just wondering why you chose such a convoluted PrintWriter when
out = new PrintWriter(sock.getOutputStream(), true);
seems to do the trick…
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.
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.
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

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
client cannot send the msg.
it appears error3 in ServerClient.
anyone?

Thanks Sushant for this Tutorial. Great!!!
Can you add “function Client receive data from Server”. ???
Thanks you !
Reply
Thanks Sushant for this Tutorial. Great!!!
Can you add "function Client receive data from Server". ???
Thanks you !
Reply
It is not working…there is no error but message is not sending to the server emulator..please help
Reply
[…] 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

hi im using android 2.3.3 .. and this code is crashing.. is there a working code for 2.3.3
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

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
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
Hi
can i transfer image using this method because the size of image is must larger. Does size matter?

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

Thanks man, i just tried it once more and it worked… you saved my day!
Reply
I have tried this code but its not working …
I have error 3 on client side on to the emulator
plz help me



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

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

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


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!

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
I tried using it on eclipse…
I typed at client side …whenever i click Button nothing happens…

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

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

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

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


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


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

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

como puedo hacer un socket pero este tiene varias clases, como lo puedo integrar?
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??:)
Reply
How can you run 2 emulator, when I run I havent’recieved data on server, why?
Reply

i unable to connect the emulators using this code.. plz help me to do this
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.

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

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
Is it possible to initialize socket connection between a mobile device and digital video recorder which is a server?
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.
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.
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.


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

does it works in same pc itself?? i mean to tell both server and client works in single pc.
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.
Reply
Create two emulator-5554 run MyServer and in emulator-5556 run ServerClient.
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?
Reply
I also got the error3 when i press submit…
please help me….
manu didi u got the error resolved?
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
Reply
I have problem with my client class as exception throws plz help me
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

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


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


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

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
hey i am getting the exception(android.os.NetworkOnMainThreadException) on running ServerClient programm please help me.
Reply
hey i am getting the exception(android.os.NetworkOnMainThreadException) on running ServerClient programm please help me.
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!!

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

[…] can use sockets for it. See here and […]
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
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….
Reply