Skip to content

Incorporating Socket Programming into your Applications

March 27, 2010

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

222 Comments leave one →
  1. April 4, 2010 3:34 am

    Awesome post! Very instructional and nicely written!

    Can you tell me the function of the break statement on line 62 please?

    • April 5, 2010 1:57 am

      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

  2. meiyen permalink
    May 25, 2010 11:14 pm

    Dear jwei512
    how can i set the ServerActivity in the background of android?

  3. nic permalink
    May 27, 2010 10:37 pm

    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

  4. nic permalink
    May 27, 2010 10:40 pm

    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

  5. nic permalink
    May 28, 2010 12:06 am

    Hi jwei,

    After I see the DDMS log, and I fixed it now. Thanks !

    • June 9, 2010 9:50 am

      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?

      • June 20, 2010 4:58 pm

        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

  6. new permalink
    June 17, 2010 9:36 pm

    R.layout.server

    Its giving error on this line . what i have to add in the layout? Please help

    • June 20, 2010 4:39 pm

      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

      • Shaista Naaz permalink
        August 26, 2010 4:30 am

        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.

      • Shaista Naaz permalink
        August 26, 2010 5:11 am

        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.

      • Shaista Naaz permalink
        August 26, 2010 5:19 am

        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

      • August 26, 2010 7:09 pm

        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

      • bloo permalink
        September 26, 2011 10:48 am

        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!

  7. Waqar permalink
    June 17, 2010 11:33 pm

    jwei512
    I am new to Android. I wanted to ask how to run this code … ???

    • June 20, 2010 4:38 pm

      Well it depends on what you have set up so far…

      Have you created a working, compilable Android project yet?

      – jwei

  8. djl permalink
    June 24, 2010 7:03 pm

    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.

    • July 22, 2010 5:16 am

      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

      • Vikram Bodicherla permalink
        June 12, 2011 3:44 pm

        You could always implement the silent sms via the C2D mechanism.

  9. Emanuel permalink
    June 27, 2010 9:35 am

    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

    • bloo permalink
      September 28, 2011 11:26 am

      Hi Emanuel,

      I was wondering if you managed to develope this application? I’m trying to do the same

  10. July 6, 2010 8:58 am

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

  11. James Ford permalink
    July 7, 2010 12:56 am

    Great post!

    But I dont get it to work with emulator -> phone.

    • July 7, 2010 5:16 pm

      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

      • March 22, 2011 8:19 pm

        hi jwel

        how can i do it with phone and the emulator?

      • May 2, 2011 1:38 am

        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

      • May 10, 2011 2:48 am

        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

    • Waqar permalink
      July 7, 2010 9:02 pm

      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

      • karthik permalink
        August 2, 2010 9:18 pm

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

      • August 5, 2010 7:41 am

        What exactly is the question?

  12. sai krishna permalink
    July 11, 2010 11:32 pm

    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.

  13. Vikram permalink
    July 22, 2010 8:59 pm

    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

    • July 23, 2010 7:29 pm

      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

  14. Joe Guzzardo permalink
    August 23, 2010 9:54 pm

    Hello Jwei,

    Your Socket Programming tutorial was incredibly useful. I owe you a drink if you ever find yourself in Chicago.

    Thanks, Joe

    • August 24, 2010 3:13 am

      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

  15. Ben Buie permalink
    August 27, 2010 6:25 am

    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.

    • August 30, 2010 3:42 am

      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

      • Ben Buie permalink
        August 30, 2010 7:11 am

        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!

      • Joe Guzzardo permalink
        September 15, 2010 4:12 am

        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.

  16. Sergio permalink
    September 5, 2010 11:10 pm

    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?

    • September 7, 2010 2:49 am

      Hey Sergio,

      Where is it giving you the null pointer error exactly?

      – jwei

      • Sergio permalink
        September 7, 2010 7:15 pm

        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,

  17. suppi permalink
    September 6, 2010 6:52 am

    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.

  18. zkwentz permalink
    September 18, 2010 7:32 pm

    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.

  19. tibo permalink
    September 24, 2010 2:21 pm

    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

  20. Russell permalink
    October 25, 2010 11:14 pm

    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.

  21. giks permalink
    November 17, 2010 2:16 pm

    im very new to android …. i m running code in eclipse im not able remove that findViewById(R.id.server_status); error

  22. giks permalink
    November 17, 2010 3:17 pm

    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

  23. giks permalink
    November 18, 2010 4:23 am

    im getting error please help …im running emulators

  24. Kusumi permalink
    November 18, 2010 11:39 pm

    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

  25. November 20, 2010 6:31 am

    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!

    • Roy permalink
      February 13, 2011 3:24 am

      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

  26. Azhar permalink
    November 25, 2010 5:06 am

    couldnt get the line 43
    Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
    from client side…

    ServerActivity.SERVERPORT where is define???

    • franklin permalink
      February 7, 2011 12:50 am

      i also having same error…

      • vivek permalink
        April 18, 2012 3:09 am

        same here

      • richie permalink
        September 25, 2012 4:04 am

        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.

  27. Lowell permalink
    December 11, 2010 10:45 am

    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

  28. Lowell permalink
    December 11, 2010 10:48 am

    For some reason my manifest didn’t paste:

  29. Lowell permalink
    December 11, 2010 11:53 am

    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;

  30. DataSmith permalink
    December 12, 2010 10:39 pm

    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 !

  31. December 14, 2010 6:51 pm

    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.

    • December 18, 2010 6:33 pm

      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

  32. December 16, 2010 5:04 pm

    I needed to put this into my AndroidManifest.xml file to get around a “java.net.SocketException: Permission denied” error:

  33. nina permalink
    December 19, 2010 11:24 am

    i have to share file between android phone and pc . any one can help for it.

  34. nina permalink
    December 25, 2010 11:53 pm

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

  35. Sunil permalink
    February 9, 2011 6:08 am

    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();
    }
    }
    }
    });
    };

  36. Slavne permalink
    February 10, 2011 4:30 am

    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.

  37. MusA permalink
    February 16, 2011 5:11 am

    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?

  38. Ruth permalink
    February 17, 2011 5:57 am

    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.

  39. February 19, 2011 1:53 am

    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

  40. March 5, 2011 3:08 am

    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

  41. tom Jeff permalink
    March 8, 2011 12:03 pm

    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

  42. droidix permalink
    March 10, 2011 8:19 pm

    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

  43. sheela permalink
    March 19, 2011 1:09 am

    when this is run on eclipse IDE, I get an error “Cannot instantiate type handler”…what does it mean?

  44. Martin C. permalink
    April 3, 2011 5:57 am

    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.

  45. Simeh permalink
    April 7, 2011 11:38 pm

    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

  46. kool4u permalink
    April 11, 2011 9:18 pm

    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.

  47. srikanth permalink
    April 19, 2011 5:59 pm

    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

  48. Erick Melo permalink
    April 20, 2011 7:13 am

    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?

  49. Jaysen permalink
    April 20, 2011 7:25 pm

    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?

  50. April 21, 2011 12:37 am

    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

  51. April 29, 2011 5:53 am

    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

  52. Baatar permalink
    May 15, 2011 5:09 pm

    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?

    • November 2, 2011 10:18 am

      Hey Baatar,

      See my new posts on integrating Google App Engine with Android applications.

      – jwei

  53. Dgenoves permalink
    May 16, 2011 5:24 pm

    nice post… i learn a lot but if i wanted to send a file or a picture.. what do i need to do???

  54. July 11, 2011 11:13 am

    Hi

    Very intuitive article,

    kindly advise why you use the IP address “10.0.2.15” and port no “8080”.

    Thanks

  55. July 12, 2011 12:07 am

    Please ignore my previous message.
    Thanks

  56. August 11, 2011 1:20 am

    Hi Jwei ..
    Can It connect using one phone and one emulator …?
    Ok thanks a lot

  57. Eric Lundgren permalink
    August 11, 2011 4:17 pm

    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

  58. Ov3rPlOop permalink
    September 6, 2011 11:19 am

    Ho dude ! that’s a great topic !
    Fanboy of your work now 🙂

  59. KhangPT permalink
    October 3, 2011 10:41 pm

    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

  60. October 10, 2011 8:46 pm

    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

    • November 2, 2011 10:32 am

      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

      • November 2, 2011 11:57 am

        Thank you! I appreciate it!

  61. October 13, 2011 3:09 am

    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

    • November 2, 2011 10:23 am

      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

  62. November 6, 2011 6:47 pm

    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

  63. November 16, 2011 2:24 am

    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.

  64. omar permalink
    November 21, 2011 6:52 am

    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?

    • omar permalink
      November 23, 2011 5:59 am

      Could not detect internet connection even if it is connected to my wifi? how come? are you still active? please thx

  65. November 22, 2011 5:59 am

    Thanks for this tutorial. But when I run this code, The application said that it doesn’t detect any connection. I’m so confuse ..

  66. November 29, 2011 11:39 am

    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

  67. Davor permalink
    December 1, 2011 3:22 pm

    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.

    • December 8, 2011 8:03 pm

      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

      • Davor permalink
        December 13, 2011 8:25 am

        Thanks for the answer, I’ll look at this post you gave me. When can we expect your post about HTTP requests?

  68. HunterX permalink
    December 12, 2011 2:06 pm

    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

    • bhagya permalink
      February 13, 2012 9:52 am

      same doubt!
      thanx
      Bhagya

  69. abhisheksrinath permalink
    January 28, 2012 8:27 am

    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 ?

    • April 3, 2012 6:34 am

      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

  70. January 29, 2012 3:24 pm

    Amazing example! Tip: When testing between a phone and an Android tablet, I could only get it working when BOTH are on wifi.

  71. sanjeev permalink
    January 31, 2012 12:54 am

    Can i do the port redirection in the java code(server) itself. I do not want to use the console for that.

  72. bhagya permalink
    February 10, 2012 5:27 am

    BRAVO!! loved d coding n helped a lot… 🙂

  73. Priyanka permalink
    February 18, 2012 3:28 pm

    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

  74. March 5, 2012 9:49 am

    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

  75. March 8, 2012 2:32 am

    love this, thanks a lot 😀

  76. March 12, 2012 7:01 am

    can u teach us to do same using c2dm???

  77. salik permalink
    March 27, 2012 1:31 am

    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.

    • Ameya Pethkar permalink
      April 18, 2012 10:28 pm

      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

  78. alison ding permalink
    May 3, 2012 10:39 am

    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?

  79. Andorider permalink
    May 6, 2012 11:54 pm

    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?

    • May 8, 2012 12:51 pm

      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

  80. May 10, 2012 10:01 am

    thanks you, very useful for me

  81. anarche permalink
    May 27, 2012 2:38 am

    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 🙂

  82. truyenle permalink
    June 7, 2012 9:41 am

    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

    • truyenle permalink
      June 8, 2012 11:40 am

      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

  83. chin permalink
    June 20, 2012 11:42 am

    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?

    • June 20, 2012 12:34 pm

      Hi Chin,

      What’s the error exactly?

      – jwei

      • chin permalink
        June 21, 2012 8:41 am

        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,

  84. June 20, 2012 12:04 pm

    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.

  85. James Stafford permalink
    July 25, 2012 7:57 pm

    Good Tutorial. Helped me a lot with my research project for my university.

  86. lab permalink
    August 1, 2012 2:04 am

    Simple but Very Good Example. Also good code structure.

  87. Ignatius permalink
    August 3, 2012 6:03 am

    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

    • August 6, 2012 9:01 am

      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

  88. johnpeter permalink
    August 13, 2012 10:41 am

    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.

    • August 14, 2012 4:31 am

      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

  89. fuhao permalink
    August 20, 2012 8:18 am

    Hi, my phone is on 3g network and has a dynamic ip. will this app work for my home.

    Thanks

    • August 20, 2012 10:39 am

      Hi Fuhao,

      Yes it will work – you just need to type in the current IP address each time you connect.

      – jwei

      • fuhao permalink
        August 21, 2012 3:56 am

        thanks for you help.

      • aishu permalink
        March 11, 2013 5:18 am

        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?

      • March 11, 2013 7:44 pm

        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

      • aishu permalink
        March 11, 2013 9:25 pm

        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?

  90. pratik permalink
    September 13, 2012 3:38 am

    Really Good Post . Thank You 🙂

  91. Solenoid permalink
    September 13, 2012 1:08 pm

    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.

    • September 14, 2012 9:04 am

      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

  92. Hanny Udayana permalink
    September 16, 2012 8:23 am

    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

    • September 17, 2012 5:49 am

      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

      • Hanny Udayana permalink
        October 13, 2012 1:31 am

        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?

  93. September 19, 2012 2:39 am

    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 🙂

    • September 19, 2012 4:48 am

      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

  94. September 20, 2012 2:22 am

    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 .

  95. hemanta permalink
    October 4, 2012 2:39 am

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

  96. October 18, 2012 3:51 am

    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.

    • October 22, 2012 5:14 am

      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

    • arvind permalink
      October 22, 2012 5:18 am

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

  97. Ali permalink
    October 30, 2012 1:24 pm

    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 🙂

  98. Akshay permalink
    November 10, 2012 6:34 am

    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 ?

  99. November 27, 2012 10:44 am

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

    • November 29, 2012 6:40 am

      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

      • November 29, 2012 9:00 pm

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

  100. December 6, 2012 9:00 pm

    I’m trying to connect two devices over WIFI, but I get a host unreachable error. What could be the problem?

    • December 7, 2012 7:42 am

      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

      • Teng permalink
        January 11, 2013 10:18 am

        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

      • January 11, 2013 11:26 am

        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

  101. January 8, 2013 7:29 am

    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

    • January 11, 2013 11:19 am

      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

      • Teng permalink
        January 12, 2013 8:26 am

        Hi Jwei,
        thanks Jwei, is there any other way for them ( 3g to wif) to communicate ??

        Teng

  102. Teng permalink
    January 13, 2013 8:54 am

    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 ?

  103. rahul permalink
    January 29, 2013 7:14 am

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

    • February 1, 2013 1:54 pm

      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

  104. Umair permalink
    February 3, 2013 9:44 am

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

  105. February 5, 2013 9:17 am

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

    • February 5, 2013 9:22 am

      Nvm. I got it by removing the break; after the while loop!

      Thanks a ton!

  106. Giselle permalink
    February 7, 2013 6:40 am

    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

  107. RPS Deepan permalink
    February 12, 2013 5:42 am

    awesome post dude! thnkz…

  108. kopiaka89 permalink
    February 15, 2013 10:33 am

    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.

  109. Tania permalink
    February 27, 2013 10:20 am

    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 🙂

  110. March 4, 2013 9:49 am

    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?

  111. Ryan permalink
    March 21, 2013 5:25 am

    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?

  112. kartavirya permalink
    March 21, 2013 6:47 am

    i want my client to receive messages from server as well, what are the extra coding that i have to add ?

  113. Keerthi permalink
    March 31, 2013 5:58 am

    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…

    • April 14, 2013 8:44 pm

      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

  114. Neil permalink
    April 1, 2013 11:23 am

    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?

    • April 14, 2013 8:45 pm

      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

  115. Ola permalink
    April 9, 2013 12:43 am

    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.

  116. Rajeshwari permalink
    May 23, 2013 2:17 am

    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.

Trackbacks

  1. Let's try it
  2. MediaPlayer doesn’t send HTTP request? - Question Lounge
  3. Android powered robot tank » Tamlyn
  4. Developer blues... Why bother? - Page 2 - BlackBerry Forums at CrackBerry.com
  5. Peer-to-peer via UMTS « Veritas crudus
  6. Socket 생성 및 Server/Client 예제 « ::: engineered eyes
  7. Socket 생성 및 Server/Client 예제 « ::: engineered eyes
  8. Technology And Software » Incorporating Socket Programming into your Applications « Think Android
  9. Send string from android to visual basic 2010 - feed99
  10. Socket on Android « san script
  11. Incorporating Socket Programming into your Applications « Think Android « Vladimir Morozov
  12. Research internship in Japan « Michael Yao
  13. Whether I can send some messages to a remote phone using soc | Android Development tutorial | Android Development tutorial
  14. Socket Programming in Android « Personal Blog
  15. How to create a server for android application : Android Community - For Application Development
  16. not able to get sockets programming to work on two android phones, port forewarding or some other cause? video
  17. not able to get sockets programming to work on two android phones, port forewarding or some other cause? video
  18. not able to get sockets programming to work on two android phones, port forewarding or some other cause? : Android Community - For Application Development
  19. Android P2P file transfer : Android Community - For Application Development
  20. How can I handle multiple clients connected to a server using sockets? | BlogoSfera

Leave a reply to Néstor González Cancel reply