Incorporating Socket Programming into your Applications
Hey everyone,
Haven’t posted in a while. Here’s something new that I came across and thought might be useful. This post is for anyone who has wanted to create an application that could communicate with another phone running your same application.
The idea involves Socket Programming and basically letting one phone be the “server” and the other phone be the “client”. Now, I don’t know if this is standard practice for letting two phones communicate with one another, but it worked for me in a new application that I’ve been working on, and so here it is:
public class ServerActivity extends Activity { private TextView serverStatus; // default ip public static String SERVERIP = "10.0.2.15"; // designate a port public static final int SERVERPORT = 8080; private Handler handler = new Handler(); private ServerSocket serverSocket; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.server); serverStatus = (TextView) findViewById(R.id.server_status); SERVERIP = getLocalIpAddress(); Thread fst = new Thread(new ServerThread()); fst.start(); } public class ServerThread implements Runnable { public void run() { try { if (SERVERIP != null) { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Listening on IP: " + SERVERIP); } }); serverSocket = new ServerSocket(SERVERPORT); while (true) { // listen for incoming clients Socket client = serverSocket.accept(); handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Connected."); } }); try { BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String line = null; while ((line = in.readLine()) != null) { Log.d("ServerActivity", line); handler.post(new Runnable() { @Override public void run() { // do whatever you want to the front end // this is where you can be creative } }); } break; } catch (Exception e) { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones."); } }); e.printStackTrace(); } } } else { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Couldn't detect internet connection."); } }); } } catch (Exception e) { handler.post(new Runnable() { @Override public void run() { serverStatus.setText("Error"); } }); e.printStackTrace(); } } } // gets the ip address of your phone's network private String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e("ServerActivity", ex.toString()); } return null; } @Override protected void onStop() { super.onStop(); try { // make sure you close the socket upon exiting serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
Before moving on to the client side of things, let’s just try and digest this together (for those who are familiar to Socket Programming much of this will look familiar – this is simply meant to be an integration of Socket Programming with the Android platform). In our onCreate() method we first retrieve the IP address that the phone designated as the “server” is on. This will work regardless of whether you’re on WIFI or 3G and is required for the client to connect to you. As soon as I get the IP address I kick off the server thread. Notice that it’s important you open and close all of the connections in a thread as the call:
Socket client = serverSocket.accept();
is blocking / synchronous / will stop the progression of your code until an incoming client is found. You definitely don’t want to put this on the UI thread as it will completely choke up your application, and so we throw it into a background thread. Now, the thread itself is pretty self explanatory. Notice how all of the serverStatus text updates are wrapped around handlers (this is necessary as you can’t touch views in the UI from a different thread without a handler). Then, once the client is retrieved, we open an inputStream() from the client and use a BufferedReader to retrieve incoming messages from the client.
This is where you can be creative.
You can do pretty much whatever you want at this point. Namely, you could create a mini scripting language (i.e. send messages like “GO BACK”, “TURN LEFT”, “START MUSIC”, “GO TO URL xxx”, etc) and have the server phone respond to those messages, and you could even have the server write messages to the client as well and have the client respond to those messages. Basically, everything before hand was just the annoying technical stuff that is required for the connection between the two phones to get established – once it is established you can send whatever form of data between the two phones as you’d like and this is where you can have fun in your future applications.
The last thing to notice is just that we override onStop() to close the serverSocket. Again, the serverSocket.accept() call is blocking, and so if we don’t close the serverSocket upon stopping the Activity it will actually continue to listen for incoming clients (until your phone kills that thread of course) and this can be problematic as it will block all future attempts to connect to the port number you designated.
Now for the client side of things:
public class ClientActivity extends Activity { private EditText serverIp; private Button connectPhones; private String serverIpAddress = ""; private boolean connected = false; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.client); serverIp = (EditText) findViewById(R.id.server_ip); connectPhones = (Button) findViewById(R.id.connect_phones); connectPhones.setOnClickListener(connectListener); } private OnClickListener connectListener = new OnClickListener() { @Override public void onClick(View v) { if (!connected) { serverIpAddress = serverIp.getText().toString(); if (!serverIpAddress.equals("")) { Thread cThread = new Thread(new ClientThread()); cThread.start(); } } } }; public class ClientThread implements Runnable { public void run() { try { InetAddress serverAddr = InetAddress.getByName(serverIpAddress); Log.d("ClientActivity", "C: Connecting..."); Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT); connected = true; while (connected) { try { Log.d("ClientActivity", "C: Sending command."); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket .getOutputStream())), true); // where you issue the commands out.println("Hey Server!"); Log.d("ClientActivity", "C: Sent."); } catch (Exception e) { Log.e("ClientActivity", "S: Error", e); } } socket.close(); Log.d("ClientActivity", "C: Closed."); } catch (Exception e) { Log.e("ClientActivity", "C: Error", e); connected = false; } } } }
Overall pretty simple. Just create some kind of EditText field that allows the user to input the correct IP address (which should be showing on the server phone) and then some kind of button that grabs the inputted IP address and tries to kick off a client thread which attempts to connect to that IP address on the specified port. Notice that the port numbers have to be the same in addition to the IP address. Once a connection has been made then everything else is pretty simple – just create an OutputStreamWriter and a BufferedWriter that allows you to send messages to the server. Then once the server receives those messages, it can respond to them in whatever way you want it to!
So yes, basically this code snippet / example is for anyone who wants to write some kind of application that works best when two phones are connected or talking to each other. Again, I’m not sure if this is how you’re supposed to go about it, but after searching for a while and eventually giving up and then finally coming across this Socket Programming idea in one of my classes, it seems like this method at least works!
So yes, happy coding everyone and hope this was interesting/helpful.
– jwei
Trackbacks
- Let's try it
- MediaPlayer doesn’t send HTTP request? - Question Lounge
- Android powered robot tank » Tamlyn
- Developer blues... Why bother? - Page 2 - BlackBerry Forums at CrackBerry.com
- Peer-to-peer via UMTS « Veritas crudus
- Socket 생성 및 Server/Client 예제 « ::: engineered eyes
- Socket 생성 및 Server/Client 예제 « ::: engineered eyes
- Technology And Software » Incorporating Socket Programming into your Applications « Think Android
- Send string from android to visual basic 2010 - feed99
- Socket on Android « san script
- Incorporating Socket Programming into your Applications « Think Android « Vladimir Morozov
- Research internship in Japan « Michael Yao
- Whether I can send some messages to a remote phone using soc | Android Development tutorial | Android Development tutorial
- Socket Programming in Android « Personal Blog
- How to create a server for android application : Android Community - For Application Development
- not able to get sockets programming to work on two android phones, port forewarding or some other cause? video
- not able to get sockets programming to work on two android phones, port forewarding or some other cause? video
- not able to get sockets programming to work on two android phones, port forewarding or some other cause? : Android Community - For Application Development
- Android P2P file transfer : Android Community - For Application Development
- How can I handle multiple clients connected to a server using sockets? | BlogoSfera
Awesome post! Very instructional and nicely written!
Can you tell me the function of the break statement on line 62 please?
Hey Sidharth,
Sorry for the confusion. In my application I have a break statement there because I’m only accepting one client connection, hence as soon as that one connection closes and stops sending me data (Line 52), I tell it to break out of the while loop in Line 39 and essentially stop listening for new incoming clients.
Depending on the behavior of your application you’ll have to handle that part differently, i.e. if you want that while loop to continue and you want the server socket to continue to listen for incoming clients then you obviously wouldn’t want to break out of that while loop (but you’ll probably want to add some logic that breaks out of that while loop eventually haha).
Hope that makes sense.
– jwei
Dear jwei512
how can i set the ServerActivity in the background of android?
Using a thread or an async task? Is that what you’re trying to get at?
– jwei
May be you can start a service instead of Activity.
http://developer.android.com/reference/android/app/Service.html
Hello,
I am a very new of android programmer. When I put this into my program. It was force closed. Is it related the permission? I add the following permissions. It was still force closed.
Thanks
May be the tag make the permissions hidden. I add them again.
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.INTERNET
android.permission.CHANGE_WIFI_MULTICAST_STATE
What’s the error in the DDMS logs?
– jwei
Thanks, this worked.
Hi jwei,
After I see the DDMS log, and I fixed it now. Thanks !
Hi,
I would like to know why I cannot connect to another phone unless I am on a private network? The logcat says:
06-09 11:40:06.186: ERROR/ClientActivity(3068): java.net.SocketException: The operation timed out
Any ideas or suggestions?
Hm, maybe in your case the connection was unstable and that’s why the operation timed out?
When I’ve done it I’ve even gotten it to work through just regular 3G on both phones which definitely is not a private network…
– jwei
R.layout.server
Its giving error on this line . what i have to add in the layout? Please help
You just need to add a TextView with the id server_status.
By looking at the first few lines of my code (inside the onCreate() method) you should be able to guess the XML structure of the R.layout.server.
– jwei
Hi,
I am also getting same error at line R.layout.server
I have added the TextView with id server_status but this solves error for line R.id.server_status but R.layout.server is not getting resolved. 😦
I am not able to guess the XML structure of R.layout.server 😦
please kindly suggest.
jwei.. does this means that I need to create a file called server.xml and put it in layout folder? if yes, then what should be the content of this file.
yuhu.. 🙂
I renamed main.xml to server.xml and the error is out.. 🙂
I am trying to make socket communication from two emulators.
And I am expecting more problems.
Nyways your tutorial is too good and thanks a lot!!
thanks,
Shaista
Yes so the problem is you probably created a file called “server” and not “server.xml”.
This XML file needs to be put into your layout folder, and inside it must be a TextView with the correct ID.
– jwei
I solved it! sorry about that! was a very silly question, you can see now how new I am to this! thanks for the great code!
jwei512
I am new to Android. I wanted to ask how to run this code … ???
Well it depends on what you have set up so far…
Have you created a working, compilable Android project yet?
– jwei
Nice. Have you considered putting the server Android’s IP address and port into an SMS message and sending it to the client Android, which, upon receipt of the SMS message, automatically wakes up (like a Push Registry) and connects to the server Android device? That way there is no need for manual inputs of IP addresses.
Ah interesting idea djl.
Though it’s probably much more convenient, could there be potentially other issues such as using up people’s text messages, etc. Is there even a way to send a “silent” SMS? In other words to intercept it on the other end with a receiver but not have the message actually show up in their SMS inbox?
Just some initial thoughts.
– jwei
You could always implement the silent sms via the C2D mechanism.
Hello jwei512,
I’m new in the android platform. I need to develop an app that allows voice-to-voice between android phones. Can you give some advice how to accomplish this. Your program seems very useful for me. I looking for sockets tutorials but I haven’t found any useful material.
Thank you,
Emanuel
Hi Emanuel,
I was wondering if you managed to develope this application? I’m trying to do the same
Awesome post! Thanks so much.
I’m NOT new to Android programming but I AM new to Socket programming. I’m trying to do RTP programming and it’s supposed to be sent over UDP sockets. Am I correct that the Android class Socket uses TCP? If so, how can I set up a UDP socket?
Again Thanks again!!!
See this http://developer.android.com/reference/java/net/DatagramSocket.html
– jwei
Great post!
But I dont get it to work with emulator -> phone.
Hey James,
Yea the emulator won’t work so well because the IPs are all local IPs to the emulator (I believe they’re like 10.0.02 or something) and it’s not easy to get two copies of an emulator communicating with each other through a socket.
I’d recommend either testing it on two phones with 3G, or between a phone and an emulator.
– jwei
hi jwel
how can i do it with phone and the emulator?
Hey Rusiru,
The phone and the emulator, when both connected to a network (either Wifi or 3G) still have IP addresses. For the emulator it would just be the local IP address (something like 10.0.0.2) and for your phone you would just need to go to your settings and check.
– jwei
hey jwei,
Thanks for the reply i tried to connect the emulator with the phone but the emulator doesnt detect the phone and vice versa how can i solve it ?:(
-rusiru
Please refer to the following document for getting this program to connect two android emulator instances. Worked perfectly for me. Thanks jwei.
http://developer.android.com/guide/developing/tools/emulator.html#connecting
even i’m new to this android… trying out socket programming….
i refered your link… i’m getting confused regarding port setup he has explained…. can u help me out??? please..
What exactly is the question?
Hi jwei,
I am very new to Android. Could you please let me know how does this code works…Like I need to connect the android device to the emulator…Which I have to use as server and which I have to use as client? Thank you in advance.
Hey Sai,
I’d start with this article:
http://developer.android.com/guide/developing/tools/emulator.html#emulatornetworking
I think this will help a lot.
– jwei
Hi jwei,
Nice post.
I am new to Android and implementing an app on desktop that can track if the android device is online or not, and if it is, wake up an app on device.
Is there any way to check if android device is online?
thanks,
Vikram
Hey Vikram,
What exactly do you mean by “online”? Do you just mean having internet access? Or do you mean being able to detect that the phone is actually awake and the user is using it at that moment?
– jwei
Hello Jwei,
Your Socket Programming tutorial was incredibly useful. I owe you a drink if you ever find yourself in Chicago.
Thanks, Joe
Haha hey Joe,
Funny you say that – I’m interning at DRW in Chicago right now =P
But no worries glad I could help!
– jwei
Correct me if I’m wrong, but this wouldn’t work if the server was NAT’d behind a firewall, right? Forgive me if I didn’t read the article closely enough and this was mentioned (or if I’m just wrong). My understanding is for this sort of thing to work reliably in all cases, you basically have to make both android devices clients and then have an intermediary server (broker) in the middle (you could use AppEngine for this).
Very helpful code regardless.
Hey Ben,
So my understanding and knowledge of NAT isn’t very thorough (I just know it’s a way of re-routing one IP address space to another), but this works without having to have an intermediary server.
I’ve demoed it before with a little prank app that I wrote (but never released haha) which was basically a remote control fart machine. I had one phone be the client (i.e. the remote control) and another phone be the server (i.e. the fart machine), and everytime the client pressed the remote control I would send a message through the socket connection to the server and the server would play a fart noise.
Sorry I can’t be more specific about how all this network routing stuff works – so far I just know that if you grab the IP address from both phones and try to connect with one another it works regardless of how the data is getting routed from one phone to the next.
Hope this helps.
– jwei
There is no NAT with a typical mobile phone connection, the problem would really only occur when you are doing WiFi. That is because in a NAT situation (with a WiFi router), the only IP address you can use is the IP address of the router (the IP Address of the phone would be something like 192.168.x.x, a non-routable address). So, unless there is port forwarding set up on the router (there isn’t going to be, unless you have control over the router, like in a testing situation), your attempted connection would get dropped by the router.
However, like I said, for people who don’t have WiFi on their phones (or don’t use it), this is a non-issue. I don’t know of any mobile data connections that are NAT’d.
Regardless this code is really cool and helpful – you can basically take it and modify it slightly for use with an intermediary server (basically both ends become clients). Other benefits of an intermediary server would be a) more graceful handling of connection issues (can store and forward the message for when the recipient has a sketchy data connection), b) not having to know the IP address of the recipient, c) not having to worry about if the recipient’s IP address changes, and d) platform independence – there are smartphones (I think iPhone?) that don’t allow inbound socket connections for security reasons. Of course, the biggest downsides of an intermediary server would be cost and scale (over time). Hard to justify a one-time fee (or FREE) for an App if there is a server to maintain 🙂
If I have time I might take this code and see if I can post an example on here showing how you could do this with AppEngine (or something similar) as an intermediary, just for kicks. That’s a big if, but I’ll try to find time if you and other people are interested.
Thanks again for posting the code!
I’ve been working on an Android game app that you can play across the web. I want to be able to play it thru a WiFi connection where both users are on the same local area network or on different networks. I came across this link: http://www.makeuseof.com/tag/find-ip-address-mobile-smartphone/ . If both users are on the same LAN then the ip address you want to use will most likely be something like 192.168.x.y, whereas if you’re communicating with someone on another LAN then your ip address will start with different values. Use one or the other address depending upon how you’re connected to the other person.
Hey Jwei, my drink offer still stands and I’d be interested in bringing your fart application to market, basically a high tech whoopie cushion. Sounds like fun and we can share the revenues on the click thru ads. If you’re still in Chicago, the Phoenix restaurant is said to have the best dim sum in town.
Thanks again for your insights.
Hi,
I ve tried the “Server Code” but I cant make it work since it starts giving me a Null Pointer Exception. What am I doing wrong?
Hey Sergio,
Where is it giving you the null pointer error exactly?
– jwei
Whenever it tries to enter any of the:
handler.post(new Runnable() {
@Override
public void run() {
serverStatus.setText(“Connected.”);
}
});
also, the application gives me an error if I add the @Override,
Hi….
a very good article on socket programming.
Well i am trying to achieve the same between android emulator as server and pc as client.
Could you please tell me how i would send messages to each other.
Hey,
First off great article! Serious, good stuff. I do have one question though and it’s about timing out. Say my Android phone is trying to connect, after 30-45 seconds without receiving a response from the server, I’d like for the connection to timeout and end the thread. How would I go about implementing a timeout? I get how to stop the thread, but how an I keep track of how much time it has taken?
Also, I noticed you put the Handler in there but you never used it. Perhaps you could go into why one would need to use that for other newbies coming across your tutorial? As I understand it, it’s mainly for doing something within another running thread, like the UI thread.
Thanks again for such a thorough, well-written article.
this code works great, but now i’m testing on my real phone HTC Wildfire and the server is listening on a local adresse like “10.47.160….” (found on the interface rmnet0). Is that OK ?
I supose I need the public one , the one i can read when i visit a websie like http://www.ip-address.com wich is more like “62.201.142….”.
thanks
Yea I believe you need the public IP address.
hey Jwei512. i’ve just started learning about Android.
and i was doing something along the line on what you have written.
i was wondering why is it that when i took the code into eclipse, there were so many errors.
Sorry in advance if i asked any obvious and easy questions.
Hey Russell,
What errors are these exactly?
– jwei
im very new to android …. i m running code in eclipse im not able remove that findViewById(R.id.server_status); error
when i run now im getting error like this and application is forced to close
[2010-11-17 18:12:24 – DeviceMonitor]Sending jdwp tracking request failed!
[2010-11-17 18:14:27 – ddms]null
java.lang.NullPointerException
at com.android.ddmlib.Client.sendAndConsume(Client.java:571)
at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:142)
at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:65)
at com.android.ddmlib.Client.getJdwpPacket(Client.java:670)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
[2010-11-17 18:14:27 – ddms]null
java.lang.NullPointerException
at com.android.ddmlib.Client.sendAndConsume(Client.java:571)
at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:142)
at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:65)
at com.android.ddmlib.Client.getJdwpPacket(Client.java:670)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
[2010-11-17 18:14:47 – DeviceMonitor]Adb connection Error:An existing connection was forcibly closed by the remote host
[2010-11-17 18:14:48 – DeviceMonitor]Connection attempts: 1
[2010-11-17 18:14:50 – DeviceMonitor]Connection attempts: 2
[2010-11-17 18:14:52 – DeviceMonitor]Connection attempts: 3
[2010-11-17 18:14:54 – DeviceMonitor]Connection attempts: 4
[2010-11-17 18:14:56 – DeviceMonitor]Connection attempts: 5
[2010-11-17 18:14:58 – DeviceMonitor]Connection attempts: 6
[2010-11-17 18:15:00 – DeviceMonitor]Connection attempts: 7
[2010-11-17 18:15:02 – DeviceMonitor]Connection attempts: 8
[2010-11-17 18:15:03 – DeviceMonitor]Connection attempts: 9
[2010-11-17 18:15:05 – DeviceMonitor]Connection attempts: 10
[2010-11-17 18:15:07 – DeviceMonitor]Connection attempts: 11
im getting error please help …im running emulators
Hi Sir.
I am trying to develop an Android Application using socket programming.
This info from your blog is quite useful.
However, I would like to ask If the import (import java.util.*;) for the code that you have given.
Or much better, maybe I can have a copy of the .java and .xml files of the project so that I can run it on eclipse.
Thanks
You need to do this in a Service, not an activity. Activities are designed such that one is active at a given time. Spinning off threads from an activity to use in other activities is not a good idea.
Otherwise, not bad at all!
Hi Derrick, I new to Android (making the transition from vb.net – which isn’t as easy as I imagined). Could you please furnish an example of how this would be done in a service. If you could , could you please include something basic like the server replying to messages like “date” and “time” perhaps. This would help me greatly…
Thanks
couldnt get the line 43
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
from client side…
ServerActivity.SERVERPORT where is define???
i also having same error…
same here
You can change ServerActivity.SERVERPORT into the actual server port you need.
The writer use ServerActivity.SERVERPORT is because ServerActivity.SERVERPORT has appeared in the ServerActivity. It means that both server and client activity are in the same program. So the writer can just use ServerActivity.SERVERPORT defined in server activity.
The following code generates an exception “Permission denied” on the “new Socket”
String serverIpAddress = “64.150.183…”;
int serverPort = 9801;
Socket socket = new Socket(serverIpAddress, serverPort);
My manifest looks like this:
I guess I’m not setting permissions right? Thanks for help.
Lowell
For some reason my manifest didn’t paste:
Anyway, I put a android:name=”android.permission.INTERNET”
after the /application and it doesn’t throw an exception, it just seems to die and never get to the “connected = true” statement…
String serverIpAddress = “64.150.183.132”;
int serverPort = 9801;
Socket socket = new Socket(serverIpAddress, serverPort);
connected = true;
Hi, jwei !
I am happy to find a good socket tutorial. But it doesn’t work on 3G connection. It would be very helpful if you would explain why it doesn’t work and how do you get over a vpn and nat servers in your code.
Thank you !
Awesome post.
I just have a minor confusion as to using server sockets.
Could you please tell me why you did a client/server?
Could we do a client/client kind of communication?
If instead of using a server socket, can we use a normal socket (similar to the client side)? Could we use the connect/bind functions of Socket, instead of ServerSocket?
Basically I’m wondering if I can implement the same functionality you have shown here, without SerSockets and just using Sockets?
Thank you very much.
Hey Maduranga,
I think reading this would be helpful:
http://download.oracle.com/javase/1.4.2/docs/api/java/net/ServerSocket.html
Explains what a ServerSocket is and gives you an idea of how it differs from a Socket. I think the main difference is that a ServerSocket listens for incoming connection requests and can fork off several connections concurrently (i.e. multiple sockets can connect to the same ServerSocket). But again, reading the documentation above will probably give you a much more detailed explanation.
Hope this helps.
– jwei
I needed to put this into my AndroidManifest.xml file to get around a “java.net.SocketException: Permission denied” error:
i have to share file between android phone and pc . any one can help for it.
hey i have to create a server as java application on pc and a client on android then they share files .how i create socket between these two application????
I am running server & client in 2 different AVD’s (emulator).
Server has started listening to the clinet.
Client is just showing a “EditText” to enter ServerIP address. After entering the serverip, if the click “connect_phones”, click button is not working.
Can you please let me know why click on listen is not working?
Here is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
Log.v(TAG,”ClientActivity1″);
connectPhones.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
Log.v(TAG,”ClientActivity2″);
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals(“”)) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
});
};
Ben Buie was right about his last comment. The programs are not usable for real situation if two phones are trying to use 3G (HSDPA,…) connection for their communication even if they are on the same local network (10.x.x.x, 172.xx.xx.xx or 196.168.xx.xx) simply because NAT wan’t route them directly. Ben said it correctly.
Only if two phones are using fixed IPs direct connection would be possible.
How can I used this code creating an Eclipse Project?
I mean, I already created a project in eclipse, but how can I run that?
I got this working on 2 emulators:
Started the emulator that will be used by the server app, and redirected port 5000 to 6000 (at cmd prompt, do ‘telnet localhost 5554’, then ‘redir add tcp:5000:6000).
Then, run server on that emulator, listening on 10.0.2.15:6000.
Next, run client on another emulator, connecting to 10.0.2.2:5000.
Notes: WinXP, Eclipse Helio, using Android 2.2.
Thanks everyone for their comments!
I hope my post was able to benefit people as much as this thread did haha – definitely picked up a lot of networking knowledge from this!
– jwei
Thank you for sharing.
I initially made the mistake of trying to use port 23(Telnet) as the server.
But Android OS already uses that port for something, douh.
The eclipse project for server side is here if you need something ReadyToRun 🙂
http://www.mediafire.com/?qattwo81s1bty9l
jwei,
Does the server application actually work when on the cellular data network? Seems like the cellular providers would block incoming connections to the device???
-tjeff
When I saw the code and the responses, I thought you guys gotta be kidding around..! A real server application on Android device is not possible but only a simple one like this which is capable of letting a few clients to get connected to server is possible.. However, the idea of having a nice client application is logical..! So never ever think that you would ever able to have a server application on an android device (maybe with multiple cores and rooted device at kernel level).. So even it’s a client socket application also accepting a connection, it would never be feasible for anything serious unless implemented at native level which is hard to implement on an embedded device with limited resources. But it is fine to play around and sending some data forth and back 😉 for fun.!
Sometimes also Android devices use proxies and firewalls 😉 so no way for two device to get connected..!
Enjoy it
when this is run on eclipse IDE, I get an error “Cannot instantiate type handler”…what does it mean?
Jwei,
You state “Just create some kind of EditText field that allows the user to input the correct IP address (which should be showing on the server phone) and then some kind of button that grabs the inputted IP address and tries to kick off a client thread which attempts to connect to that IP address on the specified port. Notice that the port numbers have to be the same in addition to the IP address. Once a connection has been made then everything else is pretty simple – just create an OutputStreamWriter and a BufferedWriter that allows you to send messages to the server. Then once the server receives those messages, it can respond to them in whatever way you want it to!”
Can you provide a small example of what the editable text field for a user to input the ip and port, and a button that gets the ip and port text and sends it to the destination socket?
I am working on a self directed project similar to this, and am stuck on how to do this.
Thank you in advance,
MC.
Hi Jwei,
Do you have an example for Android to PC communication interface / protocol using USB cable? Are they using the same socket programming way described in this article? Thanks much
Thanks jwei great post , i have learned a lot from this post.
i not able understand this line
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT)
it giving error on “ServerActivity.SERVERPORT ” can i replace my port number.
Does this code work for 3G connection? i have tried it but it is not working and for mobiles at two different WiFi networks too. Please help me with this
Hi guys,
I’m beginning with Android and I’m having problems to implement this sample in the Android Emulator… I get create the server and the client Apps, but I can’t test it because I didn’t find the Server IP (I didn’t find where is it set in the emulator).
Is possible to set the emulator to work as a Bridge or to set a static IP to the Android Virtual Device?
I know this was posted awhile ago, sorry for beating a dead horse.
Been writing Java for a few years now and I wanted to learn about sockets. I copied your code into two separate apps (Client and Server). I can follow along with the code, but I’m having trouble understanding some things.
What I am trying to do. Client xml has TextEdit for Host, button for Connect and seek bar. Server has two TextViews, 1 for status, the other for the slider position on the client.
The client connects and sends the position of the slider, but then the status changes to Öops. ” When I comment out the line on the server side the status remains as connected.
Questions:
1) Where am I supposed to put the code to set the TextView’s Text = position of the slider that the client sent over? Like what line? Anywhere I place it keeps making the server disconnect.
2) Does the code above keep the connection open, or does the client disconnect after sending the message? If so, how do I why doesn’t the server update the status to “Listening”again?
HI Jwei,
can you give me suggestion, that how could I make Client/Server Socket Communication by this code, like a instant application where all clients are connected with single server.
Adeel
hello jwei
i work with this code it show error on this line pls help
line:
handler = new Handler();
error:
Cannot instantiate the type Handler
Hi, your post is very helpful to my current project. But, can tell me how to send data(text lines) from computer to my android application?
Hey Baatar,
See my new posts on integrating Google App Engine with Android applications.
– jwei
nice post… i learn a lot but if i wanted to send a file or a picture.. what do i need to do???
Hi
Very intuitive article,
kindly advise why you use the IP address “10.0.2.15” and port no “8080”.
Thanks
Please ignore my previous message.
Thanks
Hi Jwei ..
Can It connect using one phone and one emulator …?
Ok thanks a lot
Best thing i’ve read in months. Thanks dude.
And btw, you gotta be the most patient guy i’ve ever seen :d
Keep up the good work.
Eric
Ho dude ! that’s a great topic !
Fanboy of your work now 🙂
hi jwei512,
Thanks for this tutorial, it’s so useful. But I just got a little issue: when I try to connect to one android phone(listenning incomming request from another android device), I got an exception:
java.net.SocketException:no route to host
I’m using wifi connecting. So, what should I do in this case? Anyone can help me, thanks a lot
Hi Jwei,
I realize you get a lot of tangential questions, so I apologize.
I was wondering if you could point me to any resources to help me get started learning how to implement a server. My goal is to save data externally and have it accessible from multiple phones through the use of a pin number for access, and also for the server to receive data from one phone and broadcast it to multiple phones.
How could I set up a scalable way to do that? I have never worked with servers before…
Thank you in advance for any advice!
-AJ
Hey AJ,
Because of your comment and others along the same line – I decided to make a series of posts on setting up a Google App Engine project (i.e. something that acts as a server) and then using this server to interact with a mobile client application.
Check it out! Hope it helps.
– jwei
Thank you! I appreciate it!
Hey Jwei 512..
If I want to create a library management system via using socket programming :), Is it same as we use socket programming in Java?? actually Im new andriod user 🙂 So need some guide 🙂
Thanks
Habib
Hey Habib,
Yes the concept is the same and much of the code is the same as the Android SDK is quite similar to the standard Java libraries.
– jwei
Hi Raymond,
Yea that should be fine. It’s probably easiest if you just make HTTP requests from the client side to the PHP based server. To get a sense of this follow my new Google App Engine series.
– jwei
From my experience in C++/C# if you receive a lot of data from a socket, creating an object with new (like new runnable) is a performance issue.
wow i hope this is active because it would be great if you can help me
I’m new in android and I’m planning to connect my Android to a pc/laptop using wifi
is it possible when it is connected to the pc via wifi using the its ip
when i open the video cam it will be seen on the pc or laptop?
or do i need to make a program on the pc?
Could not detect internet connection even if it is connected to my wifi? how come? are you still active? please thx
Thanks for this tutorial. But when I run this code, The application said that it doesn’t detect any connection. I’m so confuse ..
Hello Guys!!
I’ve tried to run client and server on two separate emulators. but it didn’t work out for me. i’ve fixed other errors but my application shuts down unexpectedly 😦 and below are the messages from LogCat. Please any one can help me ??? Thanks
____________________________________________________________
11-29 19:33:36.051: D/AndroidRuntime(571): Shutting down VM
11-29 19:33:36.059: W/dalvikvm(571): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
11-29 19:33:36.070: E/AndroidRuntime(571): Uncaught handler: thread main exiting due to uncaught exception
11-29 19:33:36.122: E/AndroidRuntime(571): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{server.activity/server.activity.ServerActivityActivity}: java.lang.ClassNotFoundException: server.activity.ServerActivityActivity in loader dalvik.system.PathClassLoader@44c07820
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.os.Handler.dispatchMessage(Handler.java:99)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.os.Looper.loop(Looper.java:123)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.ActivityThread.main(ActivityThread.java:4363)
11-29 19:33:36.122: E/AndroidRuntime(571): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 19:33:36.122: E/AndroidRuntime(571): at java.lang.reflect.Method.invoke(Method.java:521)
11-29 19:33:36.122: E/AndroidRuntime(571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11-29 19:33:36.122: E/AndroidRuntime(571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-29 19:33:36.122: E/AndroidRuntime(571): at dalvik.system.NativeStart.main(Native Method)
11-29 19:33:36.122: E/AndroidRuntime(571): Caused by: java.lang.ClassNotFoundException: server.activity.ServerActivityActivity in loader dalvik.system.PathClassLoader@44c07820
11-29 19:33:36.122: E/AndroidRuntime(571): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
11-29 19:33:36.122: E/AndroidRuntime(571): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
11-29 19:33:36.122: E/AndroidRuntime(571): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-29 19:33:36.122: E/AndroidRuntime(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
11-29 19:33:36.122: E/AndroidRuntime(571): … 11 more
11-29 19:33:36.230: I/dalvikvm(571): threadid=7: reacting to signal 3
11-29 19:33:36.857: I/dalvikvm(571): Wrote stack trace to ‘/data/anr/traces.txt’
11-29 19:33:46.360: I/Process(571): Sending signal. PID: 571 SIG: 9
Hey Jwei,
great tutorial. I need some advice, I need to implement a server on android (emulator) which will handle HTTP requests from a web app on the pc…how can I establish the connection between app and server? is it similar to your implementation? Thanks.
Hey Davor,
No you won’t really need anything like this which is more for open sockets between servers and clients… what you’re looking for is going to be more along the lines of my most recent post https://thinkandroid.wordpress.com/2011/11/27/google-app-engine-http-requests-3/ as well as the next post which will talk about how you can make HTTP requests from the app which hit the server.
– jwei
Thanks for the answer, I’ll look at this post you gave me. When can we expect your post about HTTP requests?
Hey Jwei 512.
Great Work,
I want to send (image / video streaming) using socket programming,
If you have any Idea or guide please help me
Thanks
HunterX
same doubt!
thanx
Bhagya
Hi Jwei,
I want to develop a very simple chat application using socket programming. In which a program must behave as a client and server so how can I do that ?
In the program which you have explained I can start sending the messages only after the client initiates the request to the server right ?
Hey Abhishek,
Yes that’s correct – the client must initiate the request, and once the socket has been accepted and opened then the client and server can freely communicate.
To do a simple chat program between two phones, I don’t see why you couldn’t make the requester of the chat the client, and the receiver/accepter of the chat the server. From there, any message that gets sent FROM the client (i.e. from phone A) to the server (phone B) simply gets displayed on phone B’s UI, and any message that phone B sends to phone A (server to client) get’s displayed on phone A’s UI.
– jwei
Amazing example! Tip: When testing between a phone and an Android tablet, I could only get it working when BOTH are on wifi.
Can i do the port redirection in the java code(server) itself. I do not want to use the console for that.
BRAVO!! loved d coding n helped a lot… 🙂
Does this code work when only 3g connection is enabled in between the two android phones?? I want to do something like a client-server communication between two android peers but only using 3g
Hi
I am looking to transfer data from a peer to multiple peers at the same time on Android..Is there any code snippets to which i can refer??
Thanks in advance
love this, thanks a lot 😀
can u teach us to do same using c2dm???
i hav run the server code on my android phone. it says “could’nt detect internet connections”. can two mibiles having this app communicate with one another through wifi or internet in must.
Hi,
I am having a bit problem with running the code.
For some reason the client is not able to connect with the server.
The Log cat says Network reachable
I just want to know what the problem can be?
Also in the client what is the significace of
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
ServerActivity,SERVERPORT cant we just hardcode the port number
Also when i try to connect the server phone with the laptop it works fine.
Let me know if some knows about the problem
Hey, nice post, I understand the necessary of making the server side multithreading, but what about client side, why we need to make it multithreading?
I think with this solution you cant create an application for dynamic environment. I mean you hard codedly put the ip address. Am I right? If so how can i create an application for the environment that changes ip while every connection startup?
Hey Andorider,
No this code does not require a hard coded IP address – the way that it is set up right now is that you can specify whatever IP address you want, at which point the socket will try and connect with that IP address/port.
– jwei
thanks you, very useful for me
Thanks Jwei … I need help abouth socket programing . How can i stop connection ? Im trying so much thing last two days but i cant stop . I will use your code for start an application whit a button in other device . But program is continuous repeating and i cant stop the application . Thnx 🙂
Very great post jwei512. I was able to connect two phones using this code.
I also have a question
In the server side
I have a TextView to show the “string” sending from client. So under the handler for creativity, I add this line of code
receivedCommand.setText(line);
as:
handler.post(new Runnable() {
055
@Override
056
public void run() {
057
receivedCommand.setText(line);
}
060
});
Before that, I also make line become a private variable for the ServerActivity class.
private String line = null;
This is to make sure line is accessible inside the handler.
In the client side
when connected, I don’t send any string but leave it as GUI interface for user to send separate strings like “Next”, “Previous”, “Hide”, “Show”.
The weird behavior happen:
when client connect to server for the first time, user then send the above strings, but the receivedCommand TextView doesn’t update. I then re-connect to the server, then upon connected although users haven’t sent any string, I see the receivedCommand TextView update with all the strings send previously concatenated.
I then look at the code and see that (line = in.readLine()) != null return a false under while loop, that’s why it didn’t update the TextView.
So I add another while loop to wrap around this while loop so that to make sure the server
keep reading the Buffer like this
…
…
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
While (true) {
while ((line = in.readLine()) != null) {
Log.d(“ServerActivity”, line);
handler.post(new Runnable() {
@Override
public void run() {
// do whatever you want to the front end
// this is where you can be creative
receivedCommand.setText(line);
}
});
}
if (line == “Exit”) break;
}
Well, the behavior is the same and I don’t know what should I do in order to have the TextView update instantly when client sending each strings.
Any help would be very much appreciated.
Thanks
Truyen
It is working now. The reason is that I didn’t send \n (next line) character from client that block the call readLine().
Great. Thanks
Hi, I am trying this code to develop simple server client application for the first time, but the server code is not able to detect an internet connection. not sure what is wrong? can u help me, please?
Hi Chin,
What’s the error exactly?
– jwei
i solved that problem, i forgot to add the permission. 🙂 but after that, my server and client are not connecting to each other 😦 , there is no error but they are not communicating. the log on client is
06-21 16:39:51.091: D/ClientActivity(872): C: Connecting…
06-21 16:39:51.091: D/ClientActivity(872): C: Closed.
and server is just displaying the IP address,
my server is running on the phone and client is on emulator.
Thanks,
That was very helpful for me to do an important Android project in my university, I want to express for that my sincerely greetings to you, jwei, for your valuable code. Thank you.
Good Tutorial. Helped me a lot with my research project for my university.
Simple but Very Good Example. Also good code structure.
Good Article….But by any chance might you be having a code illustration of Android (Client) send binary data send and receive data(image/text/binary) via TCP to a C++ server am working on a project that require to connect to there server post data and retrive plus verify user password at the server
Hi Ignatius,
Is there any reason you need to do this through sockets? Have you considered instead using HTTP servlets to make GET/POST requests? For instance, you could look at https://thinkandroid.wordpress.com/2011/11/27/google-app-engine-http-requests-3/ which is just one post in a series of posts, I give an example of how you could use an external back end (like GAE) along with an Android application to accomplish tasks that you’ve listed. More specifically, GAE has protocols that allow you to send binary data, and you could also create your own authentication POST methods.
– jwei
my scenarios is
i have a device which is connected to company A’s wifi network,
and another device which connected to company B’s wifi network.
both companies are so far.
is it possible to implement the communication between these devices using your socket programming code ?
it is an urgent need?
i need to find the solution.
thanks in advance.
Hi,
Yes this is possible – in fact sockets are used to address problems like these specifically. All you need to do is specify [on the client side] what the server’s IP + port # is.
For a good introduction to sockets please read http://www.tutorialspoint.com/java/java_networking.htm.
I’d advise you to do so before trying to piece together random bits of code. Best of luck.
– jwei
Hi, my phone is on 3g network and has a dynamic ip. will this app work for my home.
Thanks
Hi Fuhao,
Yes it will work – you just need to type in the current IP address each time you connect.
– jwei
thanks for you help.
i am able to form my server and client, but i cant connect them.
On the client side, which IP address should i exactly put? is it the one that can be seen on the server when it displays “Listening on IP” in your code?
Hey Aishu,
Yes you’re supposed to put the IP address of the server. The client is trying to communicate with the server – hence it needs to know where to send data.
– jwei
My socket at the client side is not getting created. It just reaches till the “Connecting” part.
I have put the IP address of the server on the client, still it doesnt seem to work. What should be done?
Really Good Post . Thank You 🙂
Is there any way to connect to the Andorid IP via a web browser like Chrome? I tried and the phone said something was connected, but the page on my browser in the computer never finished loading. I understand very little of networking… but serving a header and content shouldn’t be THAT hard, but then again I don’t know what I’m talking about.
Hey Solenoid,
The question is a little vague as it really just depends on how you are connecting through the web browser… in theory though assuming there are no firewalls you should be able to establish a connection from your Android client to the web browser.
– jwei
Hi jwei! Thanks for your tutorial. Really helped a lot. I have something to ask you if you don’t mind. I want to make a simple chat application. With those code,the client send “Hey server!” over and over again. What should I do to make the client send it by a button press? Best regards..
-Hanny
Hey Hanny,
In the ClientThread, the section that has the while loop:
while (connected) {
…
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// where you issue the commands
out.println(“Hey Server!”);
…
}
you just need to move the PrintWriter into the onClick() method of the button. Right now since it’s embedded in a while loop, you’re going to continuously write “Hey Server” (which is consistent with the behavior you are seeing).
– jwei
Hi jwei, i’ve been away for some time.
I’ve tried moving the PrintWriter into the onClick() method of the button. But I got the networkOnMainThreadException. How could I fix it?
Can you please upload screenshots of your UI? I can’t get it to work, because of variable names of UI components that don’t exist. Other than that, good article 🙂
Hey Morne,
The UI components are pretty minimal… on the server side it is just a TextView and on the client side it is an EditView with a Button…
The TextView on the server side is just for displaying its IP (i.e. the host IP) as well as the connection status, while the EditView on the client side is for entering in that host IP. The Button is just for submitting the connection request.
The IDs of the views don’t matter – they can be anything you want.
– jwei
Hi this is Rajesh ,
while connection with two emulators from various devices i am getting this issue.
09-20 15:56:18.162: D/SntpClient(70): request time failed: java.net.SocketException: Address family not supported by protocol
Please advice me .
Hi Rajesh,
Just try Googling the error… seems to be:
http://stackoverflow.com/questions/7854300/java-net-socketexception-address-family-not-supported-by-protocol
– jwei
Thanks jwei i will have a try and let you know ….
Hi jwei,
I am new to socket programming.
Please help me.
My client application is not able to connect to server.
I created two applications. One is client (installed in device1) other one is server (Installed in device2). In Client app, line 43 of your client app code gives me Exception.
thanks in advance….
Hi Hemanta,
What’s the exception? Feel free to PM me at lets.think.android@gmail.com
– jwei
Is it possible to initialize connection between mobile phone and dvr recorder using sockets? I mean that i don’t have access to create the application on dvr recorder which actually is a server.
Hey PS,
I don’t know much about DVR recorders but given that you say it is a server it really just depends on whether or not the DVR recorder provides you with an interface to communicate with it. In order for a client to initialize a connection you must have a server listening to a given IP/port and this typically requires someone configuring the server to do so.
Hope this makes sense.
– jwei
Hi PS,
Yes.. It is possible to do that.. I tried it on a system built by Nagra Kudelski.. Let me know the details and I will try to help you..
Thanks Arvind!
– jwei
Hello jwei,
Beginning i want to admit how your article is professional and helpful.
I want to develop an app that controls PC via WiFi router (sleep, restart, etc..), but i don’t know how to start it :s
Plz help me trying to develop such an application and what if you provide me with a code I will be thankfull 🙂
Hi Ali,
Sorry I’m not seeing how this is related to Android programming – can you clarify?
– jwei
i am trying to write an android app that can control multiple PC’s connected to the same router. So the first step is to know what are the active IP’s, that be displayed by the app, connected to router in order to send packets to the desired IP i find active in the router.
Thanks for your attention 🙂
Hi Ali,
So after some research my best guess would be something along the lines executing an ADB command programmatically to retrieve the routing table of your router.
Some links that might be useful to you:
http://stackoverflow.com/questions/6940973/can-i-get-the-routing-table-entry-in-android (adb command for viewing routing table)
http://stackoverflow.com/questions/6517615/how-to-execute-adb-logcat-d-time-pathoffile-log-txt-programatically (executing adb command programmatically)
http://stackoverflow.com/questions/12001449/how-to-optain-the-ip-address-of-the-connected-wifi-router-in-android-pro-grammat (finding the IP address of your router)
Hopefully these links can get you on the right path…
– jwei
Hey hii,went through your post and its really nice and interesting . Havent tried it though. But I had this query in my mind ,here we have two devices ,can I be able to communicate with my PC from android using sockets ? If so ,then if I want to access shared files from pc to my phone ,how could this be done ? I dont want to run any client module over PC ,but all I want to do is to access the shared folders and stream video files over wifi ,ofcource ,when pc and phone are connected to same wifi router. Do you have any idea about how to achieve this ?
i understand clearly the architeture and functionality of socket and serversocket but i only want to get the server ip or server hostname on the client side through the client side socket .. Can u help plzzz…. ????
Hi babrit,
You could use a broadcast address to address this problem. The idea is that you have a “central” IP address (think a hub) which all servers initially connect to. Then when a client sends a request to this IP address, it responds with a message – in this case a list of all servers connected to it (hence this is called a broadcast address). You can read more about the idea here:
http://stackoverflow.com/questions/9446799/android-search-for-server-automatically
And for details on how to actually communicate with the broadcast address see:
http://code.google.com/p/boxeeremote/wiki/AndroidUDP
Hope this helps.
– jwei
do u think that m doing something good on it?? i mean my learning on android is going in a right way or not .. juzz wanna know nothing else..
I’m trying to connect two devices over WIFI, but I get a host unreachable error. What could be the problem?
Hi g3,
I don’t know much about this error but you could look at
http://superuser.com/questions/453933/pinging-a-machine-on-my-local-network-gets-an-unreachable-response-from-my-own
Maybe that’ll point you in the right direction.
– jwei
Hi Jwei,
I’m very new in android , will this code work with 3g because i am try to make an app that will allow my pc to communicate with my android phone through 3g. i already write a simple socket programming that will allow them to communicate through wifi but it fail to comunicate through 3g
Hi Teng,
Most networks (Wifi and 3G) use NAT. NAT allows outbound connections, but prevents inbound (internet to device) connections. Only when your server and device are both on the same network will this socket programming work because you don’t need to traverse a NAT gateway.
In other words, this kind of socket programming typically only works when multiple devices are connected to the same [Wifi] network.
– jwei
Hi jwei,
I am creating and android application incorporating neural networks and I need to communicate the GPS co ordinates of one device to the other, I am new to android programming, however, I have researched and do know how to get the gps co ordinates and proximity alert etc which I will use. I’m just unsure as to the socket programming and how to send the co ordinates from one phone to another. I’m a student and have started studying this topic this semester, so any information would be greatly appreciated.
Regards,
Dony
Hi Dony,
Have you tried following the example? If you designate one device as the client and the other as a server, I don’t see why you couldn’t send over two coordinates.
– jwei
Hi Jwei,
thanks Jwei, is there any other way for them ( 3g to wif) to communicate ??
Teng
Hi Jwei,
thanks Jwei, is there any way for them ( 3G to wifi) to communicate ?? the only way i think of is through a website, where 1 site have to write a string and save it on the website , and the other site just read from the website. but my application required fast response. it works perfectly when i using socket programming within the same wifi. is there a way for 3g and wifi to communicate and response fast ?
thanks a lot
Hi, I did the code as per your guidance. it runs well. thanks. but m stuck at a point , i want to sent string value of variable from client to server after the connection is established. how do i sent it? is it at this part of the code :-
// where you issue the commands
out.println(“Hey Server!”); —>>> here??
Hi Rahul,
Yes that’s correct. Once your client is connected to the server, you can use the BufferedWriter to then write strings. These will subsequently be read with a BufferedReader on the server side where you can respond accordingly.
– jwei
i m also new in android programming found this tutorial very nice….
i have problem in line “062” with break statement,
i want my server to listen continuously unless force closed,
i m using above code but it listens only once and executing break statement control will come to line “091”. why this break statement is terminating outer while loop?
any body please help….
Very good tutorial!! I have a doubt. In the run() function of the server i am trying to toast the line variable. Basically I want to toast the message received by the server. How do i do it? I cant toast the line variable as it says the “line variable should be a final variable”.
Nvm. I got it by removing the break; after the while loop!
Thanks a ton!
Hi,
Nice tutorial
If I want to connect between my PC (server) and android (client) via wifi.. do you have any idea how do i modify the code accordingly?
Thank you
awesome post dude! thnkz…
Hi jwei512,
thank you very much for this great example code. I’m new to Android, and that is exactly what I was looking for except for one small thing. Instead of sending from the client to the server, I would like the server to send in regular intervals to only one client. I tried to implement this using a timer, but I did not get it to work. Do you maybe have any ideas regarding a possible solution?
I would really appreciate any help, thank you very much.
Hello,
I am trying to establish a socket connection(client/server) between android and pc via wifi where it sends messages to the server(pc)…Plz help me 🙂
I’m using sockets like this with WiFi Direct. How can I code a one-to-many system where a server can talk to multiple clients?
I followed this tutorial exactly but the client can never connect. I get a socket timeout exception. The host (server) is found, but the client never successfully connects. Anybody have any idea?
i want my client to receive messages from server as well, what are the extra coding that i have to add ?
This is possible only using threads?? Bcoz i tried the same without threads, it doesn’t show any error… But it’s not getting connected…
Yea you’re going to want to use threads as the server waits for a client to connect and this occurs during a while loop – leaving this in the main thread would not be wise…
– jwei
I know this is quite old now but I have a question. Is this meant to be 2 separate applications? 1 for client and 1 for server? How can I code it into 1 application?
You can code this into one application – simply separate the client and server parts as separate Activities and let the application choose whether it wants to act as a client or a server.
– jwei
Thanks so much for this wonderful tutorial….I used an android table as the client and my cell phone as the server….works!!
Can’t wait to expand its functionalities.
Thanks for this blog. It really helps for the beginners.
I am new to android application development. I tried as you explained above but when running the code in emulator, how to segregate sever and client. When i run both (server and client) as a launcher one overwrites the other.
It will helpful if i get detail steps to execute this program.