Thursday, March 29, 2012

Simple Client-Server Application for Android


Note: Here is the updated tutorial of the following tutorial for the latest Android version:
http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html 

Following tutorial is based on Android 2.3 (API Level 10). It is not compatible with later versions since API Level 11 introduced AsyncTask implementation for network communication. Refer the above link instead for working solution. 

This application is a simple client-server application which has a Android mobile client and a Java server which is run on a machine. In this example, client is run on the Android emulator and the server is run on the local host. In Android 10.0.2.2 is the IP address for local host. This application allow to type a text message on a text field and when the Send button is press the message is sent to the server. Server continuously listen to the port. When there is a incoming message server read it and show it on the standard output.



Client Side Application



Server Side Application

132 comments:

  1. you got talent in android application!! Waiting for more info! thanks for the sharing...!!

    日本NCH

    ReplyDelete
  2. Thank you very much Akemi. Hope to bring you more in the future.

    ReplyDelete
    Replies
    1. hi is it possible to connect to the server using ur HTTP request program in the apache Tomcat server I have downloaded

      Delete
  3. It was really a nice trick it has increased my knowledge about how to increase the rate on android application..!!

    car accident lawyers in utah

    ReplyDelete
  4. I would like to thank you for the efforts that you have made in writing this article.This is exactly what I need,Thanks a lot.Keep blogging.


    disinfectant wipe

    ReplyDelete
  5. Its really nice article regarding ....about your panoramas to be able to my personal pals keeps up the excellent function heading. ...

    antibacterial wipes

    ReplyDelete
  6. This is great ...can we extend it for remote desktop

    ReplyDelete
  7. Thanks Raja. Yeah of course, We can try for that. It won't be hard task. Just configure a network connection and change the IP address of this program.

    ReplyDelete
  8. Thats not really a really huge statement, but its all I could come up with after reading this. You know so much about this subject. So much so that you made me want to learn more about it. Your blog is my stepping stone, my friend. Thanks for the heads up on this subject.


    sanitaire vacuum

    ReplyDelete
  9. This function allow to type a wording message on a wording field and when the Send button is press the note is sent to the server

    ReplyDelete
  10. I want to write a very simple application (maybe it is not so simple). ... The actual coding of this is fairly simple to accomplish. Basically you just .


    Mobile Application Development

    ReplyDelete
  11. Thanks Madhuranga, I am glad to see such a great tutorial on android's client server~ can you explain a little bit more about that "Server Side Application"? It doesnt belongs to android anymore right? it is just computer-based program? but I didnt know how to follow-up this portion, can you help me?

    Thanks in advance.

    ReplyDelete
  12. Yeah, Server isn't an Android program. It is just a Java application which is listening to the port and it reads the port when a client connects.

    ReplyDelete
  13. Hi Madhuranga, thanks for the great tutorial. It's very simple one way connection. I want the server to push data to one or more devices. What should I do?

    Thanks in advance.

    ReplyDelete
  14. You should implement a connection manager in the server side. It's not hard, really simple. Just keeping the track of each connection. If you google it, you can find many example. I will try to bring a post about that for you all.

    ReplyDelete
  15. hi
    i can not understan this part
    client = new Socket("10.0.2.2", 4444);
    the IP can I use it for any phone ??
    and what you main by 4444 ?

    thanks alot ..

    ReplyDelete
  16. it is like my project ,,
    i will send msg from phone to the laptop and then the laptop should give me the feedback >>
    can you help me to implemntet

    ReplyDelete
  17. Hi Zeen,
    10.0.2.2 is the IP address for accessing local host from Android emulator. That means, this Android application is running on the emulator and the sever also running on the same computer. If you are going to access remote server you have to change IP. 4444 is just a number for the port number. You can use any number. There are some standers port numbers also. So the code line you mentioned just creates a socket with 10.0.2.2 through port number 4444.

    ReplyDelete
  18. Ok .. can you help me to do my project ?
    I need your help ..

    ReplyDelete
  19. Ok .. can you help me to do my project ?
    I need your help ..
    It is like what you do .. but I want the server to give the user feedbak .
    How can I do it :-(

    ReplyDelete
  20. Yeah sure, actually you can use this simple application as a model. You can just create a PrintWriter instance in the server side and open a BufferedReader in the client(Phone) side. Then you will be able to communicate from server to phone. First try this as a test. Then change and implement it as your requirements.

    ReplyDelete
  21. o_O can you write the code for me .. I dont have a Goode knowledage in android

    ReplyDelete
  22. When I press send the apps freezes then crashes, using an Android HTC wildfire S with Android 2.3.5 any help?

    ReplyDelete
  23. Thank You!!! This code helped me an immense ammount when i had to do a project last minute. Keep up the good work!

    ReplyDelete
  24. i am getting errror as "Unfortunately:simpleclient has stopped working" can u suggest something please, and at server side its everything fine

    ReplyDelete
  25. hii... i tried to run this code..but the client program always shows up that "client program close unexpectedly".. help me out

    ReplyDelete
  26. Hi Princy & Karishma,
    Sorry for the late replying. Both of you are getting some generic error messages. So, I just cant figure out the what the exact reason is. Try to debug the code, then you may able to find problem.

    ReplyDelete
  27. hello
    I have tested your application.it is not working
    Server is listening
    but Emulator is not sending anything to server
    what is the issue?
    Thanks for article.

    ReplyDelete
  28. hi

    thank you for such great help and kind efforts.

    i would just like to know how to make the apk work in real time device i.e. mobile phone. the emulator works right with the ip address of the laptop as well as localhost ip address but the same apk does not work in phone.

    please do reply

    you may contact me on jahnavi.patel2@gmail.com

    ReplyDelete
  29. This client side code is not working ,Unfortunately:simpleclient has stopped working

    ReplyDelete
  30. Tried my ass out on this but its not working,,Unfortunately:simpleclient has stopped , tried debugging it all possible ways it just didnt work.

    ReplyDelete
  31. Hi everyone, this is to address the last few comments: you need to implement "asynctask" in your app code to get it work work.

    ReplyDelete
  32. Hi..
    I tried this code in my system.But it is not working.In emulator the message as
    "Unfortunately the SimpleClient has stopped".I don't no what to do.Can you help me to get rid of this error.
    Thanks In advance

    ReplyDelete
  33. Hi Madhuranga,
    Nice clean tutorial. Thank you for the efforts.
    I have 2 questions.
    1. Is it possible to have a php socket on the server side?
    2. Is it possible to include more variables into the output stream when sending message from client to server. My limited knowledge on this subject suggests I append the additional variables with delimiters into one complete string and have the server parse the string to segregate the message into different variables. Is that the right approach?

    ReplyDelete
  34. how to run this application can you to detail it? please.,.

    ReplyDelete
  35. thank you for your tutorial. btw, what about the receive code(with php) for the post request from the client side ?

    ReplyDelete
  36. Worked like charm... Thanks for the simple and useful tutorial

    ReplyDelete
  37. Won't work for me :/ Client crashes

    ReplyDelete
  38. Hi, I used your code to test the android client and java server application, but the server is not able to display anything which I type from my client. I have created a android application file for client side and running a java application for the Server side. The server is listeneing for the data on the port , that's what it is showing but does not show me any other message. Is there anything I might be missing?

    ReplyDelete
  39. Added AsyncTask and the application worked ! Thanks

    ReplyDelete
  40. Thanks you very very very.................much!

    ReplyDelete
  41. great demo.... works well when done with async task!

    ReplyDelete
  42. Can someone explain how you used async task. You have to extend the asynctask right? But in the client the Activity class is extended so how can you extend this class as well?

    ReplyDelete
  43. @Madhuranga, Shouldn't you be using on the server side? AFAIK ServerSocket calls are blocking so this server would only accept a single simultaneous client connection because. Is that correct?

    ReplyDelete
  44. no result
    nothing happening
    please help

    ReplyDelete
  45. error showing me in the java class please help...

    Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: sim
    pleserver/Main)

    ReplyDelete
  46. Can you please tell me project file structure to create this app...

    regards
    Krishh

    ReplyDelete
  47. Hi Madhu great exercise ... i put this in my phone but its not working what should i do in regards with that...what changes should i bring to the code??

    Thank you

    ReplyDelete
  48. Hello Everyone.

    I am making an app for medical device. But the problem is that I am not able to send datas too and fro to the medical device.

    Can anyone please help me.

    Thanks alot in advance

    ReplyDelete
  49. hey... i need your help.
    If you can give me some time then please contact me on
    mayur.nalwaya93@gmail.com

    ReplyDelete
  50. Hi

    I would like to try out your program, but sadly i receive an error by compiling. From where can be downloaded the project?

    ReplyDelete
  51. Can u do this in reverse as well? Like make the server on android an client on PC

    ReplyDelete
  52. Great job! I am actually starting to learning android development.
    I would be really interested if you can do some android lessons by example application.

    I also run dev related blog. You can find it on http://devmain.blogspot.com

    Cheers!

    ReplyDelete
  53. hiii,
    can you help me in my project " Remote desktop access using android"
    suggest me from where to start with?

    ReplyDelete
  54. hi it was greate but its crashed full with error in my my android please help me and there some one typed AsyncTask what is this please put in the coad here thansk waiting for your reply thanks bro

    ReplyDelete
  55. How to handle more than one client, can be said 8 or more

    ReplyDelete
  56. how i compile server file and run i have no idea please tell me

    ReplyDelete
  57. can we connect android phone as server client via bluetooth

    ReplyDelete
  58. Hi,

    I am going to access remote server.I changed IP. Then I run server and client in different PC(machine). but server didn't get any thing from client. what can I do? I should change something in server side?

    Thanks in advance,
    Srwe

    ReplyDelete
  59. What is asynctask ? How can i put it in the code ? Would this run on actual device also ? or only emulator. The app is crashing.

    ReplyDelete
  60. Hi,

    i wanted to know if i can use
    client = new Socket("http://testserver.com", 4444); in place of
    client = new Socket("10.0.2.2", 4444);

    ReplyDelete
  61. hi this not complete so how can i receve data from server??????

    ReplyDelete
  62. @Madhuranga
    bro can you please post the working .apk here
    Thanks

    ReplyDelete
  63. how do i implement with java.nio?

    ReplyDelete
  64. where to write server side coding in this app?

    ReplyDelete
  65. i am new to client server communication.also new to android. i need to stream a video live.. from my phone to a laptop. any leads for that?

    also, could you tell me, how do we execute .once we have all the code..up ..like normally we do start server first for it to listen right?
    so how do we only start that file..

    ReplyDelete
  66. I want the code of two way socket programming in android..in whc when client send msg to the server on button click then server listen that msg and also response at the same time.Plz help me immediately...

    ReplyDelete
  67. hey can u tell how to use asyctask in this code ?

    ReplyDelete
  68. I got this error FATAL EXCEPTION: main

    ReplyDelete
  69. can we use both client and server as an android emulator or mobile ??

    ReplyDelete
  70. Hi there, I've been looking at your code and it seems to be exactly what i need. Unfortunately the code doesn't work any more, I've tried to salvage some of your code and put it in a working project of mine but now that one crashes too. I've seen people talk about using asyncTask but I haven't got the slightest clue how to use it. Could you please help us?

    ReplyDelete
  71. Hi All,
    Thank you very much for all your comments. I am sorry for this late response. It's true, as most of you have experienced above application doesn't work with current Android versions. Above tutorial is based on the Android 2.3 (API Level 10).
    But with Android 3.0 (API Level 11), AsyncTask was introduced for network operations. The reason is Android has decided to separate main UI thread from other time consuming operations (like network communication) for better UI experience. In the above tutorial i have opened a network connection in the main activity thread. Therefore, this is not going to work anymore.

    I wrote a new tutorial with the AsyncTask. It works fine with the latest Android versions. Please refer this new tutorial instead of above tutorial.
    http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html
    If you have any issue, feel free to post a comment. :-)
    Thanks and regards.

    ReplyDelete
  72. what if androidmanifestxml is not there?

    ReplyDelete
  73. thanks all of prlease any one can help me how can i made reservation system but both side is andriod client serve

    ReplyDelete
  74. Hi! Will this work 4 jelly bean. THNX.

    ReplyDelete
  75. Hi. The theme is very interesting. Thank you.
    May be worth more to give an example where the C # server and the client for android?

    ReplyDelete
  76. Hey Allan, thanx for this nice tutorial! Do you have an idea how or is it possible to send each letter unique, when u hit a letter on the keyboard and for example if u wrote sth wrong u can delete letters. So what my app shoul do is: When Client is typing its alrdy displayed on the screen of the Server. Is this possible and if yes how can i do this?
    thank you in advance!

    ReplyDelete
  77. Hi Anonymous on Oct 30,
    I'm not Allan by the way. ;-)
    You can do it. You just want to modify listener to the text field which capture the key press event and push it to the sever in each time you press a key.

    ReplyDelete
  78. Hello, looking for a life saver... Is it possible the the server side App be in PHP ? and for this to work SERVER and CLIENT MUST be on the same network ? Is there a way to make it work over the internet instead of network only. Thanks in advance

    ReplyDelete
  79. thank you very much! but im new in android and dont know how to modify this listener. how and where can i capture these key press events and push them to the server? do u have perhaps a link or tutorial for this? :)

    ReplyDelete
  80. This tutorial no longer support for new Android versions. Please refer my updated tutorial instead from here: http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html

    Capturing the key press event of the button is not a big deal. Following few lines do it for you. :-)

    button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

    // Do whatever you want here when the button is pressed

    }
    });

    ReplyDelete
  81. Thank you very much for this fast answer! I knew what u mean! But your answer is only for pressing "selfmade" buttons right? i wanna capture the pressed buttons on the keyboard, which automatically appears when u click on the textfield? Or am i wrong and this is the same?

    ReplyDelete
  82. I don't have a clear idea on what you are going to do exactly. Do you want to send each letter to the sever side which your pressed?
    If so, you should bind a key event listener to the text field.
    Or can you describe me the whole thing you want to do exactly?

    ReplyDelete
  83. Hey Madhuranga,
    here is Anonymous (November 16) again! Yes, that's exactly that what i wanna do! Can u give me the code to bind a key event listener to the text field? I'v no idea how to do that :/
    thank you so much! I rly need to know how to do this for my project.

    greetz

    ReplyDelete
  84. If you search on internet you can find many example regarding this. Following is the simplest way to capture a keyboard event on the Text Field (In android context EditText).

    textField.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {

    // Here you can implement what you want to do.
    // You can use keyCode to identify the pressed key.

    return true;
    }
    });

    ReplyDelete
  85. i want to write data on port from server side and read the same on android device how do i do it..?

    ReplyDelete
  86. Can you swap the functionality of server and client ?

    ReplyDelete
  87. Yeah or course. But please try following version of tutorial. :)

    http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html

    ReplyDelete
  88. nyc tutorial sir
    I connected to server using asynctask method. But for receiving data from server using runnable method, and am unable to receive the data. Please give a solution.

    ReplyDelete
  89. Hi Madhuranga Lakjeewa you have wrote awesome blog. I am new to computer programming language i am beginner in java and android programming hence i am trying to write a code for make a android app for sharing keyboard and mouse event with server(PC with java app) can you provide me some code or some links or suggest any book where i can find how it will work. its important for me.

    ReplyDelete
    Replies
    1. Hi Yagnesh,
      I'm bit confused about your requirement. "an android app for sharing keyboard and mouse event with server". There are no any mouse events in Android. But you can capture the key press events. Can you please clarify this? :)

      Delete
    2. First of all thanks for your pop reply. yes actually i want to make an app like Remote Mouse(https://play.google.com/store/apps/details?id=com.hungrybolo.remotemouseandroid&hl=en) for sharing keyboard and mouse.

      Delete
    3. Got it :), you want to operate your PC mouse and keyboard through your Android device. It's not simple task which i can explain everything in a comment (But don't be disappointed, it's not much complex at the same time :)). I will try to write a blog post regarding this, but i can't be sure that i will do it soon. Anyway i will tell you guidelines so that you can follow.
      You may have to write two programs. One is for your android device (Android app) and the other one is for your PC (Sever program). You can execute the action from Android app and it will communicate with the server program and pass the action to the server program. Sever program will call to the PC operating system API's and execute the relevant mouse or keyboard action.
      There are few important things you should be really consider.
      1. You should create a network and connect your android device and PC. Probably you can use Wifi or Bluetooth connection types.
      2. The PC program (Sever program) may really be depend on the PC operating system since it should call the internal API's to execute the action event. Therefore you may not be able to one sever program which works for all operating systems. You may have to write several server programs for each operating system if you want to use your app with different OS's. But if you are happy with an one OS (lets say only Windows) you may have to write only one server program.

      Hope this will help. :)

      Delete
    4. Thanx dude i have started to work on your guide lines but i hope you will also post the code i will wait for that i have 4 months to complete this program. You just wrote awesome and easy to understand blog post for every beginner android developers. Thanx again.

      Delete
  90. Why everytime I run the code of java it will return the output in to this.
    Exception in thread "main" Server started. Listening to the port 4444
    java.lang.NullPointerException
    at simpleServer.main.main(main.java:37)

    can anyone help me with this problem? Good Day :)

    ReplyDelete
    Replies
    1. This is an outdated version of Android. Please refer this new tutorial for latest Android versions.
      http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html

      Delete
  91. Hi
    i ran this code successfully in android emulator with PC.But i want to know how to run this app in android device with PC through WIFI.
    Can you send the Procedure to my email.

    ReplyDelete
    Replies
    1. Wifi is a network technology. You can create different types of networks using that technology. One simple way is creating a wifi hotspot using your PC and connect the Android device to that network. If you are using a Windows OS, here i have described how to do it.
      http://lakjeewa.blogspot.com/2014/08/share-laptop-internet-connection-with.html

      Delete
    2. And what if i what to run this app through my mobile connection...

      Delete
  92. now wat to do when we have to send a message from server side to android client ...

    ReplyDelete
    Replies
    1. Follow this[1] tutorial. Then you will lean how to do what you want to do. :)
      [1] http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  93. hello. nice work mate!can you help me i have a web application and i want an android application to send messages and photos to the web application and get feedbacks from web app.help me please. Thanks in advance

    ReplyDelete
    Replies
    1. What you want to do is not much complex than this tutorial. You just want to do is creating a normal web service (which can read a message and send a feedback) and access that web service using your Android app. I can't describe each and every step here in a comment. But if you search in google, you may be able to find many resources and sample code regarding this.

      Delete
  94. Hii developer..As I only know to develop stand alone apps in android..Now I want to start with developing client/server communication apps..I don't know what are the resources(I mean s/w except eclipse) that are used to develop these type of apps. So can you suggest what resources are needed..? I can't get the sequence from where I can start..And can I start developing these type of Apps after having a knowledge of stand alone apps..

    Thanks in advance..

    ReplyDelete
  95. HI Maduranga Im getting this error when I tried to run this code
    - Syntax error on token ".", ... expected
    - Return type for the method is missing
    - Syntax error on token ")", { expected after this token
    - Syntax error, insert ";" to complete FieldDeclaration
    - Syntax error on token "textField", VariableDeclaratorId expected after
    this token

    ReplyDelete
    Replies
    1. The errors your are getting are java syntax errors in the program. If you use any IDE like Eclipse, it will help you to fix the problems easily.
      Anyway, the above tutorial has been outdated. Please refer the following tutorial instead.
      http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html

      Delete
  96. This comment has been removed by the author.

    ReplyDelete
  97. useful informative post.. thanks for sharing.

    ReplyDelete
  98. sir please tell me how i make my 1 cell phone as sever and 2nd cell as client. give me the concept about this....

    ReplyDelete
    Replies
    1. You can do it, the logic is the same. But the most trickiest part is creating network between the mobile devices. How ever the above tutorial is outdated. Go through the following tutorial instead.
      http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html

      Delete
  99. Exception in thread "main" java.lang.NullPointerException
    at com.lakj.comspace.simpletextserver.SimpleTextServer.main
    Is error found what i do?

    ReplyDelete
  100. Thanks a lot for this tutorial.

    ReplyDelete
  101. Thank you for sharing this article, it is very easy to understand and informative. Excellent!


    ReplyDelete
  102. An outstanding share! I have just forwarded this onto a colleague who was
    conducting a little research on this. And he actually ordered me lunch
    due to the fact that I stumbled upon it for him...
    lol. So allow me to reword this.... Thank YOU for the meal!!
    But yeah, thanks for spending the time to discuss this subject
    here on your site.

    ReplyDelete
  103. This site was... how do you say it? Relevant!! Finally
    I have found something that helped me. Cheers!

    ReplyDelete
  104. I think the admin of this web page is genuinely working hard in support of
    his web site, as here every stuff is quality based material.

    ReplyDelete
  105. Good post! We will be linking to this particularly great post on our site.
    Keep up the great writing.

    ReplyDelete
  106. continuously i used to read smaller articles or reviews that
    also clear their motive, and that is also happening with
    this post which I am reading at this place.

    ReplyDelete
  107. What's up, its good piece of writing regarding media print, we all know media is a impressive source of
    information.

    ReplyDelete
  108. Thank you so much for this blog. Your post is very helpful for me.

    ReplyDelete
  109. Thanks for the application you gave me, I needed this information. You keep doing your work like this.

    ReplyDelete
  110. Thankyou so much for this blog. Your article is very informative and very useful for us.

    ReplyDelete
  111. Nice information. It is very helpful. Thank you soo much.

    ReplyDelete
  112. Thanks For sharing This Type of Blog.

    ReplyDelete
  113. very informative blog for me. thanks for sharing this valuable blog with us.

    ReplyDelete