Monday, May 5, 2014

Simple Android Client-Server Application

This is an android application which sends a text message to a server. When you press the send button, the application sends the message in the text field to the server program. Here the program been written so that the client runs on the Android emulator and the server runs on the local host. IP address 10.0.2.2  can be used to connect to the local host with Android. Server program is continuously listening to the port 4444. When an incoming message arrived, server read it and show it on the standard output.
This tutorial is based on Android 4.4 (API Level 19 - KITKAT) version.



Following are the source codes of main components.

Android Text Client Application

SlimpleTextClientActivity.java



AndroidManifest.xml



activity_slimple_text_client.xml (res/layout/activity_slimple_text_client.xml)



Java Sever Program

SimpleTextServer.java


Following are the both Android client and Java server complete projects. You can clone or download them as zips from Git-Hub.

Git-Hub HTTPS clone URL: https://github.com/lakjcomspace/AndroidTextClientServer.git
Git-Hub Repository URL: https://github.com/lakjcomspace/AndroidTextClientServer
Download as a Zip: https://github.com/lakjcomspace/AndroidTextClientServer/archive/master.zip
You can run the projects by importing them to the IDE. Or just create you own project and copy and paste above source files.

179 comments:

  1. nice tutorial! :D
    could u give some info of how to set IP address(client) automatically? something like get IP from server?

    thanks!

    ReplyDelete
    Replies
    1. Android Chat Head Library
      Chat head is new feature which floats on screen instead of residing inside conventional application. This feature is very continent for multitasking as user can work and chat at the same time.
      Android Chat Head Library

      Delete
  2. Hi Nero,
    I'm not that much clear on your question. Here we are not bother about the client IP address. We directly connect to the server from the server IP address (In this case it is localhost:10.0.2.2).

    ReplyDelete
  3. If put the program in android device.... how to connect? using wifi connection?

    ReplyDelete
  4. You should host your server program so that it can be accessed through your wifi network. Then just replace the IP address "10.0.2.2" with the sever IP address in the Android client program. Then Install the program on your Android device. That's all you should do. :-)

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. how to send data back from server to client

      Delete
    3. Go through this[1] blog post. You will find how to do it. :)

      [1]. http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  5. Yeah you can call me Sam.
    I have tried so many times, for instance,
    plugging a lan to the computer and set its network id to the client java,
    sharing the mobile network id to the computer and also modify the network id,
    but it cannot work on sending messages. Only successful in using emulator.
    Any solutions on this problem or have you tried this with your mobile using lan network, mobile network or wifi network?
    I am interested in knowing the difference of why emulator could run but mobile couldn't.
    Moreover I have also seen your article written in 2012/03, and in no doubt many effort had paid to try but I got no luck.
    Actually my friend and I are in teams of investigating mobile apps for academic, may I hope you to make this server client programs being possible in mobile?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  6. Hi Sam, thank you very much for your interest. I will get back to you ASP with a descriptive and reasonable answer. Because the thing you are trying to test really depends on the network and its configuration.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hello Slobodanka,
      Go through the following blog post. It describes how to create a wifi hotspot from you laptop.
      http://lakjeewa.blogspot.com/2014/08/share-laptop-internet-connection-with.html
      Connect your laptop from the Android device. Now you are done the the network.

      Change the IP address in the client program to Windows internet sharing IP (default 192.168.137.1). Install client program on the Android device and host the server on your laptop. Run the application. :)

      Delete
    3. Hello Madhuranga,

      Thanks to your answes below I managed to do that before getting your answer, and after I did it I removed my comment in order not to disturb you, but you still had answered me, thank you!
      You are amazing!

      I came back to your blog(which is my favourite so far) because i wanted to ask you a question.
      I am sending parameters and string from mobile through the network to the desktop, but now i need the server to actually reply to the mobile when the message was received. I was reading these days about GCM and android push notifications, should i try to implement it using them?
      But android push notifications aren't based on real time events, are they?

      I am sorry to disturb you, but I am not sure how to implement this, maybe it can be simplier that this, or maybe your chat application might help me in this case?

      Thank you for your answer, you are truly amazing in what you do and inspirative as well!

      My best wishes!

      Delete
    4. Hi Slobodanka,
      Thank you very much for your appreciation and complements. :)

      GCM and Push Notifications are very advanced methods when we compare with what i have done in that tutorial. Anyway, the method you should use for your app depends on your requirement. If you are creating a simple demo app like my tutorial chat application, you don't want to go for advanced things, you can simply survive from my tutorial. ;)
      But if you developing some thing real, something meant to be used by the people, you should definitely use GCM and Push Notifications. GCM and Push Notifications are basically for instant messaging applications. If you are creating WhatsApp or Viber like thing GCM and Push Notifications are ideal.
      Push Notifications is real time. It just notifies the mobile user when a new message is received while he/she is away from the application.

      Delete
    5. Hi Madguranga, :)
      It should be similar like this client - server application with the exception that as soon as the server will get the message, on the phone a notification should be received that the server got the message(the sure should know that the server received the message).

      Delete
    6. Hello again,

      While trying to work on the problem described above , I did the same thing as you for android -> server and server->android connection(printWrtiter, BuffferedReader). However, when a message is sent from the server(the server actually responds to the android device that the message from the client is received) it is not printed on the screen. I did it in the same way as for the Chat app, with the Recever, sender and ChatOperator classes, however it is not working properly. (in this case the Receiver is not working) It enters into the receiver class, but it probably never gets to the try block where it is supposed to get the message from the server.

      Do you have any propositions why that is happening, is it possible that it is confusing something? Many thanks in advance and sorry..

      Delete
    7. It seems like your the connection between the Android device and the server has not been established properly. How did you configure the network? Are you using an Android device or the emulator?

      Delete
    8. I am using the android device. I can send a string from android to the server, but when the server is supposed to confirm that it has received the message(by appearing a confirmation string on the android device screen) it is not sent, otherwise it works fine ...

      This is actually my main part of the server
      *****************************************************public static void main(String[] args) {
      try {
      serverSocket = new ServerSocket(1233); // Server socket
      } catch (IOException e) {
      System.out.println("Could not listen on port: 1233");
      }

      System.out.println("Server started. Listening to the port 1233");
      clientSocket = null;
      while (true) {
      try {

      clientSocket = serverSocket.accept(); // accept the client connection
      inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
      printWriter = new PrintWriter(clientSocket.getOutputStream(), true);
      bufferedReader = new BufferedReader(inputStreamReader); // get the client message
      message = bufferedReader.readLine();

      System.out.println(message);

      printWriter.write("The server received the message");
      System.out.println(printWriter.toString());
      printWriter.flush();
      printWriter.close();
      inputStreamReader.close();

      } catch (IOException ex) {
      System.out.println("Problem in message reading");
      }
      }

      }
      *******************************************************************

      Delete
    9. while this is for Android
      *****************************************

      private class SendMessage extends AsyncTask {
      private String messageToServer;

      @Override
      protected Void doInBackground(Void... params) {

      printwriter.write(messsage); // write the message to output stream
      String msh = new String("");
      msh += "Temperature is: " + temperatureValue + " Pressure is: " + pressureValue;
      concatenateString = msh;
      printwriter.write(msh);
      printwriter.flush();
      printwriter.close();
      return null;
      }
      }
      private class ReceiveMessage extends AsyncTask{
      private String messageFromServer;
      @Override
      protected Void doInBackground(Void... params) {
      while(true) {
      try {

      response.append("aaa");
      response.append(messageFromServer);


      } catch (UnknownHostException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      }
      }

      }

      @Override
      protected void onProgressUpdate(Void... values){
      response.append("aaab");
      response.append(messageFromServer);
      }
      }


      private class Connection extends AsyncTask{
      String msg;
      @Override
      protected Void doInBackground(Void... params){
      try{
      client = new Socket("192.168.0.108", 1233);
      printwriter = new PrintWriter(client.getOutputStream(),true);
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));

      } catch (UnknownHostException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      }
      return null;
      }

      @Override
      protected void onPostExecute(Void result){ //result from doInBackground is passed over here, in result
      messsage = textField.getText().toString(); // get the text message on the text field
      textField.setText(""); // Reset the text field to blank
      SendMessage sendMessageTask = new SendMessage();
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      sendMessageTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
      } else {
      sendMessageTask.execute();
      }

      ReceiveMessage receiveMessage = new ReceiveMessage();
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      receiveMessage.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
      } else {
      receiveMessage.execute();
      }
      }
      }
      ******************************************************************

      The thing is: the "aaa" from the ReceiveMessage is not even printed...
      // Connection is called on button click

      Delete
    10. Sorry, this is the try block for the ReceiveMesssage class ...

      try {

      messageFromServer = in.readLine();
      publishProgress(null);
      response.append("aaa");
      response.append(messageFromServer);
      }

      Delete
  7. Hello sir thank you for above information.
    Sir i need a project topic based on Client-server,
    Sir please suggest me such a topic.

    ReplyDelete
  8. Hi! thanks for this post... i'm using this as a guide to compliment a client-server chat for pc i did a few years ago and i need your help, what can i do to stop the socket from closing after the client sends a message?. It closes so i can't send a message from my server to the client

    ReplyDelete
  9. Sir i tried running this code but it is not working.Maybe because there is no androidmanifest.xml file?

    ReplyDelete
  10. Hi Shreya, Can you bit describe the error you are getting? Above you can find the AndroidManifest.xml which you want (2nd block of code, 1st one is SlimpleTextClientActivity.java).

    ReplyDelete
  11. when I tried running the client side code,it gave the error "the application may be doing too much work on its main thread"and the application stopped

    ReplyDelete
  12. Also how can i find the IP address of the android client which is communicating to the server like in this case we are printing a message,what if we want to display the ip address of the android device on the server console?

    ReplyDelete
  13. Hi! Great work, i managed to install and run on 2.3.6 android device and i wonder the solution of Sam's issue, maybe because of firewall i guess or enabling the computer on network would help

    Leo

    ReplyDelete
  14. yeah, worked

    Leo

    ReplyDelete
  15. Hi..I want to use this in my android application but where do i place the java server in order to use it on the android phone. If i have to host it..where and how should i? i really need this.

    ReplyDelete
  16. Hi Leo,
    It's great to hear. :-)
    As you experienced,it should work like charm if you have properly configure the network . Definitely that should be the Sam's problem.
    Hey Sam, i think you cant get an opinion from Leo now. ;-)

    ReplyDelete
  17. Hi Anonymous on June 15,
    Its pretty straightforward. You just want to run the sever program on your computer. If you know how to run a Java program, that's all. :)

    ReplyDelete
  18. Hi Madhuranga,
    Thanks for your immediate response.(I'm Anonymous on June 15).
    I actually dont want to run it on my computer. I'll like to install the app on my android phone and make it work like as it happens on other instant messaging apps like whatsapp.
    I'm not debugging on the computer. Please Help!!
    thank you,

    ReplyDelete
  19. This is what you should understand. Android client application and Server program are two separate entities. Above tutorial i have run both programs in the same computer. Android client application run on the Android emulator while the Server program run on the computer as a normal Java program. But you can install client application on your Android devise. Still you should run the Server program in you computer. You can not run both programs on you Android devise (it doesn't even make any sense).

    ReplyDelete
  20. hi, Thanks for the tutorial, I wanted to know how to retrieve the text from the server and show it in listview.
    thanks.

    ReplyDelete
  21. Sir how can we send message from server to client?

    ReplyDelete
    Replies
    1. Hi Shreya,
      This post[1] is regarding creating an Android client-server chat application. Go through this and you will understand how to send a message from server to client.

      [1]. http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  22. Hi Anonymous on June 17,
    Here the text is shown on the standard output (also known as console/terminal/cmd). You can just write some string processing code to use it for any other purpose. However, showing the message in a list is away from the scope of tutorial. You don't want to wait until i write about it. Just google. You can find many string processing tutorials. :-)

    ReplyDelete
  23. Hi Shreya,
    Could you understand how the Android client sends the message (using OutputStream) and server reads the message (using InputStream)?
    Just implement the same thing the other way round. Send the message from server by writing on OutputStrem in server and read the message through InputStream of client application. Try it, you can do. :-)

    ReplyDelete
  24. i want to pass texts from two fields like email and password. what should i do to pass that two texts from android client to java server at a time without closing connection.

    ReplyDelete
  25. thank you very much

    ReplyDelete
  26. Good morning Madhuranga. My name is Patrice and I'm from Canada.

    This summer I decided to finally learn how to program an android application, on my own free time, from scratch. I finally got some basic knowledge on how to use Eclipse and Java. In my app, I am now at the point where I need to learn how to create a Java Server and how to connect to it with my android app. In the past week, I've been looking for tutorials on how to do so, and I finally found yours, which seems to be the best that suit my needs. Tonight I have been trying to run it and to test it, but it seems that I can't.

    I would greatly appreciate if you could help me...

    Here's my setup, and what I have done:

    I run the java server on my Dell laptop, which is connected to the internet via my appartment building network. (with rj45 wallsocket). Using the website whatismyip.com , I found out what is my Dell's IP.

    I run the android application on my cellphone, a galaxy S3 which is connected to the internet via 4G / LTE. I installed the application on my phone via my other laptop, an Asus, using Eclipse and my phone usb connecter.

    In Eclipse, before installing your tutorial app on my cell, I modified the Ip to connect to with the one from my Dell laptop IP. I didn't change the port numbers.

    So what happened: I executed the server on my Dell laptop, then I ran the application on my phone. When I try to send the message, I received an error message:

    java.net.ConnectException: failed to connect to /(My Dell IP) (port 4444): connect failed: ECONNREFUSED (Connection refused)

    I would greatly appreciate if you could help me on this one!!

    Pat

    ReplyDelete
  27. Hi Patrice,
    Great to see your long comment and i'm really appreciate your effort. :-)

    The thing you are going to do is bit of hard. But if you can create a private network which you can directly connect your laptop and S3 you can easily run the application.

    Here the problem is with the network, not with the application. You are trying to connect two device using public network. There are lot of things happening in-between your laptop and S3. There are routers, ISP's (Internet Service Providers), firewalls, etc. You are trying to make your lap almost a web server where people can access publicly. But you are accessing internet through your apartment building network. There is a router which control this network. You may have to configure that router so that it resolve NAT. This won't be an easy task.

    If you really want to do this you may have to read and study about Networking.

    ReplyDelete
  28. Thank you so much for your answer!

    Yes, my ultimate goal is to create a server that anyone could connect to and send messages to. Ok I think I understand what you mean, since I do not own my own internet connection, I would be unable to change the settings of it so that clients may connect to it, is that what you are saying?

    What does NAT mean?

    If I understood correctly, if I plug in a wifi rooter to my internet wallsocket, that would create my own personnal private network. Therefore, I could put in the right settings into the rooter so that I could run the app on my mobile and connect to my server (laptop) through my personnal WIFI, is that it?

    If that is what you mean, once I would be ready to host the server through a real server hosting company, would it be complicated to modify the app and server source codes to make it possible for anyone with the application to connect to it, from anywhere they are?

    Another question, is there a way I could privately send you my email? I could send it to you through your linkedin account?

    Thanks again for your time!

    ReplyDelete
  29. You are always welcome. :)

    Though you have your own internet connection or public internet, you are communicating through "internet", aka public network. You can't have your own internet (network). If you can create you own network, you can do this easily. As an example you can turn on wifi of your laptop and you connect your S3 through wifi. That's a your own network. There, you don't have any complected system which you cannot control in the middle.

    NAT means 'Network Address Translation'. Just search google, you can find whole lot of detail. It would be effective than my explanation. ;-)

    Don't plug the router to your wall socket. Connect laptop and S3 trough the router. That would create a private network.

    You can just host the server program anywhere. If you can host the server in real server company, that would be the shortest answer to the problem, but not the optimal. It would waste money, because this tutorial program doesn't do any useful thing. It just reads messages. If money is not a problem for you, there you go. ;-)

    Yes, you can send me messages.

    ReplyDelete
  30. please give me more information to implement this application..plz help me to start my server

    ReplyDelete
  31. Does this wrk for Jelly Bean?? Thnx Brother!

    ReplyDelete
  32. Can we create chatting app with the help of these concept

    ReplyDelete
  33. thank you this article help me so much :)

    ReplyDelete
  34. hello Madhuranga Lakjeewa,

    can you help me in running the server side?
    i got a hard time to import in adroid elipse
    its my first time to use this language and IDE

    ReplyDelete
  35. Hey there, I would appreciate if you could tell me how to implement the server side to respond to the client?,

    ReplyDelete
    Replies
    1. Hi Javier,
      This new post[1] is regarding an Android client-server chat application. Go through this tutorial and you can understand how to send a response from the server to client.

      [1]. http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  36. When i run this app on android 4.1 (Lenovo A706), there is a Toast: Unfortunately has stopped. Could you explaint? And how to resolve?
    Thank you!!

    ReplyDelete
  37. Hi Tuan,
    "Unfortunately app has stopped" is a general error message. From that message we can only say that there is a problem. ;-)
    Try to run this app you Android development environment which is based on Android 4.1. Then scan the logcat. You may be able to find the reason. :-)

    ReplyDelete
  38. Hello Madhu,

    I ran the AndroidSimpleTextClient on Eclipse , and The SimpleTextServer on Netbeans.... I really dont see any output? Where would I be able to see the "Server started. Listening to the port 4444"
    .
    Thanks,
    Venkata

    ReplyDelete
  39. Hi Venkata,
    I hope your AndroidSimpleTextClient on Eclipse and SimpleTextServer on Netbeans ran well without any error. If so, you should see the text message on Netbeans Output Window.
    According to your question it seems like you don't have any idea about how to find the Netbeans Output Window. Isn't it?
    Just check how Netbeans shows Output window in this tutorial[1]. The message and the "Server started. Listening to the port 4444" should also be shown like same. :-)

    [1] https://docs.oracle.com/javase/tutorial/getStarted/cupojava/netbeans.html

    ReplyDelete
  40. Hi dear Madhuranga Lakjeewa,
    first of all thanks for the tutorial.

    i get the same problem of Patrice, i want to make my 'device-client' connect to my 'computer-server'.

    I make the server listen on my computer like a normal java program, on a port.
    Then i write my app with AndroidStudio and run it on my device.
    In this app, i declare a socket client with port the same port of the server and with Ip address??

    My computer is connected to my home wifi and also the device..

    So i guess i should set the Ip that Whatismyip.com says on my laptop, or the IP i find on my laptop itself in the network section of System preferences ( little question: how is possible they are different..?)

    Anw i tried with both of them but the connection doesn't start..

    Could you tell me which Ip address i should set and also, even if it is not related to this topic, why Whatismyip.com says a different IP than my network settings?

    Thanks in advance,
    Daniele

    ReplyDelete
  41. May i ask you to answer asap if you find a minute, cause i have the exam on this topic in two days...? :)

    ReplyDelete
  42. Ok i got why they are different..:) but both of them don't work anw..

    ReplyDelete
  43. This is the code of my app on AndroidStudio ( the main part of the .java file) :

    public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    String host = "192.168.0.101" ;
    //it's my 'private' IP address, that one from my network setting (or ifconfig)
    Socket s=null;
    try {
    s = new Socket(host, 7777);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }


    so the app should just start a connection to my laptop and the server listening on port 7777 should do something (like print "Connected!" ) when it receive (in this moment Socket client= server.accept(); ) the tcp (i guess) connection... but it doesn't do anything, it doesn't 'accept' my client..

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. I figured out that i was not using INTERNET permission in Manifest file and maybe this is an important thing..

    So i added


    but in this way the app crashes... if i delete that command, the app doesn't crash but doesn't even connect to the server, of course.. what to do..? do you have any suggestion?

    ReplyDelete
  46. I dont know why but my line disappeares.. i try again:

    So i added
    uses-permission android:name="android.permission.INTERNET"/

    ReplyDelete
  47. Hi Domenico,
    Sorry for the delay, I was away. You may be writing your exam today. Anyway,

    This is completely a network problem, not an Android problem.
    You are correct, you may find two different IP address in you system preferences and that site you mentioned. This is the story. Just try to understand how you connect to the internet. As an example lets order the main things you pass when you connect to that particulate IP address site (Whatismyip.com).

    Your Computer -> your home wifi router -> your Internet Service Provider (ISP) -> Whatismyip.com

    The IP your system preference shows is the IP which you use to communicate with the wifi router. That is called your Private IP address. The IP that site shows is the IP which you use to communicate with the Whatismyip.com. This is called you Public IP address. Local IP to Public IP change can be happened at your wifi or ISP (or at both places). This IP mapping process called Network address translation (NAT).

    Therefore, you cannot connect with your computer using your public IP. Your public IP is controlled by your ISP and their firewall won't allow your own connections.

    But you can connect your device and your computer using the wifi router without going ISP level. You should create a private network using your wifi. If you search you can find many examples how to do this. And then use that private network IP addresses with your program.

    ReplyDelete
  48. Hi.. Appreciated the simple clear tutorial
    Jus wanted to ask u 1 thing..
    I want to connect my phone via your app coding(client) to my emulator(will be the server) on my dell laptop.. Is this possible with this code? Or does it only work as the server side being run in a cmd window?
    Any cautions regarding the IP addresses?

    ReplyDelete
  49. Hey hi there nice tutorial but i want to ask a question what to do if i want to make a app to share a realtime keyboard(operate pc keyboard from android phone.) sharing app.

    ReplyDelete
  50. Hi YO!,
    Your question is not clear for me. Do you want to run the app on your phone and connect it with the sever which is running on your laptop?
    If so, this is a common question asked by most of readers and i have answered it before. you have to create a network between your mobile phone and laptop. You have mentioned something about windows command line (cmd). That's not clear for me. :)

    And Mr. Anonymous,
    I haven't done it before. But i think, it can be done. If you search you may find some guides or tutorial. Anyway you may have to write two programs. One is for your mobile phone and other one your PC. Mobile app can trigger the key command and PC program can receive it. Then PC program can execute the key action on PC itself. More importantly you should connect those two devices. For that you may have to crate WiFi or Bluetooth connection.

    ReplyDelete
  51. hi madhu...
    sorry if i havent been clear..
    i want to run your client program on my mobile phone as an app

    the server program i start like a regular java program in my command prompt... by compiling and running...

    javac myprog.java (compiling)
    java myprog (executing)

    .... but what if i dont want this... java prog server...

    i want the server to be my GenyMotion Emulator... and my mobile phone that runs our Client side program to connect to this emulator (which is now the server)?
    now what should i do... pls guide me.. i hope im clear..
    appreciate you taking time on my doubt.. thanx

    YO!

    ReplyDelete
  52. Ok clear. :)
    As far as i know, Genymotion is an Android emulator. Above sever program is a plain Java program and it's not an Andorid program which can be run on an Android emulator like Genymotion.
    If you want your Genymotion emulator to be the sever, you may have to rewrite the program as an Android program. That is what you should do.
    When you are done with that, you may have to create a network between you mobile phone and the emulator.

    ReplyDelete
  53. ok clear... well explained...
    just need you to point me in the direction:-

    Just as how you use " SendMessage"...
    i want to know how may i code a ReceivedMessage"

    i tried it from your java code of the server... but no success :-(

    ReplyDelete
  54. SendMessage is an AsyncTask which is running in the background to send the message. doInBackground method is triggered when someone pressed the "Send" button. But receiving a message is not an triggered action, the program should wait until a message received. You can use the server side program. Re-write it in the Android context.

    ReplyDelete
  55. hey!!
    I coded the very same client application in c#,But it seems my client is able to send text message only once,next time i enter text in text field is not sent to sever.Please help

    ReplyDelete
  56. I am new to android and i am not able to understand how pom .xml file was created and how it works in server program

    ReplyDelete
  57. Hi...i was trying to execute the above code and noticed that the apk gets installed (\SimpleClient\bin\SimpleClient.apk installed on device) but does not appear in the emulator...Also can you please let me know how to establish a connection to transfer a file from pc to android as i am new to android.

    ReplyDelete
  58. Hi Anonymous at 10:42 AM,
    You should loop like thing to capture the messages continuously.

    Hi Anonymous at 3:10 PM,
    You can just forget about pom.xml file. It's the Maven build script to the project. You can throw it away if you are not using Maven. It does't affect to the program execution.

    Hi Anonymous at 5:23 PM,
    The information you are providing is not enough to understand your issue. It can be a issue with the program or a issue with the emulator.
    You want transfer a file from "Android" to PC. I'm not sure that the term "Android" is for a Andoriod device or Android emulator. If it is the Andorid emulator you can just follow the exact steps in the above tutorial. Otherwise (For an Andoir device) you may have to create a network between the device and the PC.

    ReplyDelete
  59. how to send back message from command prompt to android app

    ReplyDelete
  60. Re-write the same program reverse order so that the server program can send message and app can receive it. :)

    ReplyDelete
  61. Hello, I am running the client and the server code files. Both the files are running correctly. But the client is not able to establish connection with the server. I modified the server code to get the IP address of the server and use this address in the client code. The code gets stuck at the line where the socket is created. I assume there is some network issue.I appreciate your help.

    ReplyDelete
  62. From where are your Android app and Server program running? (Eg: Android emulator, Android mobile device, PC, etc...). Tell me for the each component. If the both program is not running in the same computer (ie: Android app in the emulator and Server in the computer itself) this should work fine. Otherwise this would depend on the network configurations.

    ReplyDelete
  63. I am running the app on the android device and the server program on windows system.

    ReplyDelete
  64. Then you should create a private network between your Android device and the server. It won't work though you changed the IP address to your PC public IP address.

    ReplyDelete
  65. Hello sir how do i get an acknoledgement from server

    ReplyDelete
  66. Sir can u please tell me how do i get acknoledgene from server that msg is sent to it or not ,my server is on .net site

    ReplyDelete
  67. ..nice tutorial!!!!!!!!!
    but i wana know how to close the socket connection.........is it possible to do with asynctask???? pls reply

    ReplyDelete
  68. That is what has been done in line number 63 of SlimpleTextClientActivity.java. :-)

    ReplyDelete
  69. hi Madhuranga
    thanks for code
    this code cannot compile after 57.line in client code " client = new Socket("10.0.2.2", 4444);"
    i changed 10.0.2.2 and used my compter ip. and also i run server code at cmd and i run client code at emulator.
    but it didint works.
    Also i added this code

    texwievv.setText("8");
    InetAddress host = null;
    texwievv.setText("9");
    try {
    host = InetAddress.getLocalHost();
    } catch (UnknownHostException ex) {
    texwievv.setText("7");

    }

    try {

    texwievv.setText("1");
    client = new Socket(host.getHostName(), 8000); // connect to the server
    texwievv.setText("2");

    i saw 1 but i cannot saw 2.
    thank u for your attention

    ReplyDelete
  70. i could work when i delete the texwievv.setText:))

    ReplyDelete
  71. For those of you wondering about getting the client work on your phone and the server to work on your computer, here's a possible solution if your server machine is on a wifi network. What I ended up doing was enabling port forwarding on my wireless router. As Madhuranga said, this is different for every router, so you'll have to figure out how it's done on yours. But basically in your router's port forwarding settings you enter the ip address of your server computer and the port the server is listening on, and then enable port forwarding for that ip address and port. And naturally, the same principle applies to a wired router, too. But you'll need to figure out how to get into the admin settings on your router, and then where the port forwarding feature is within those settings.

    John

    ReplyDelete
  72. please tell me how to implement the server over phone. i mean , i want the to run the server as an android application on other phone , how can we do this ?? ...

    ReplyDelete
    Replies
    1. Hi Jayesh,
      You want to connect two Androids phones, don't you. So the most important thing is the network which connects the phones. The application code may not much different than the above. If you can search and find how to create the network, there your are. Anyway, that thing can't be describe in a comment. I will try to write a new blog post regarding your requirement soon. :)

      Delete
  73. Hi
    I read your article my only question is,
    What changes should i do in this code to receive response from server side ?

    THANKS IN ADVANCE.............

    ReplyDelete
    Replies
    1. It's not a change, you should add the line of codes to do that. You can use the same socket connection. You have add the implementation to both client and server side. Simply, you should do the same thing what server does in client side and vice versa.
      I can write the completed code in this comment. But i hope this guidelines will help you to do that. I will try to write a post regarding what you asked, but i wont be able to do it soon. :)

      Delete
    2. Thanks for your reply, I understood what are you saying and also successfully implemented 2-way communication.

      THANKS AGAIN...............

      Delete
    3. Hi,
      I have the same problem as akshay, i want to make a 2 way communication. I tried putting an input Stream reader in the client side but it seems to crash the android application.

      Delete
    4. Hi All,
      As i promised you Akshay, here[1] is the solution for both of you. I could find some time to write a post. This is an Android chat application. You can chat from Android Client App to PC Java program and vice versa. Your problem was how to implement two way communication. Go through this tutorial and try to understand how i have done that.

      [1]. http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  74. Hi,
    I have the same problem as akshay, i want to make a 2 way communication. I tried putting an input Stream reader in the client side but it seems to crash the android application.

    ReplyDelete
    Replies
    1. Go through this new post[1] and you will understand how to implement two way socket communication in Android.
      [1]. http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  75. Thank you Lakjeewa for your effort.

    ReplyDelete
  76. Anyway to remove the send button all together and replace the send method with enter using onKey?

    ReplyDelete
    Replies
    1. Yes of course you can do it. Remove the send button. Add a key listener for enter key inside the 'onCreate' method (Just like the send button listener has been added).

      Delete
    2. Thanks for all the help.

      Delete
    3. So within this stub:
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_slimple_text_client);

      textField = (EditText) findViewById(R.id.editText1); // reference to the text field
      button = (Button) findViewById(R.id.button1); // reference to the send button

      // Button press event listener
      button.setOnClickListener(new View.OnClickListener() {

      public void onClick(View v) {
      messsage = textField.getText().toString(); // get the text message on the text field
      textField.setText(""); // Reset the text field to blank
      SendMessage sendMessageTask = new SendMessage();
      sendMessageTask.execute();
      }
      });
      }

      I would need to replace all onClick's with onKey's and change the button to textField?

      Delete
    4. To look like this?
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_slimple_text_client);

      textField = (EditText) findViewById(R.id.editText1); // reference to the text field
      button = (Button) findViewById(R.id.button1); // reference to the send button

      textField.setOnKeyListener(new OnKeyListener() {
      @Override
      public boolean onKey(View v, int keyCode, KeyEvent event) {
      if ((keyCode == KeyEvent.KEYCODE_ENTER)) {
      textField.requestFocus();
      return true;
      messsage = textField.getText().toString(); // get the text message on the text field
      textField.setText(""); // Reset the text field to blank
      SendMessage sendMessageTask = new SendMessage();
      sendMessageTask.execute()
      } else
      return false;
      }
      });
      }

      Delete
    5. No. Just remove the whole thing starting from line number 39 to 48. Then add the following lines. Here you are adding the key listener to the text field. I haven't tested this, but this should work technically. Try this and let me know. :)

      textField.setOnKeyListener(new OnKeyListener(){
      public boolean onKey(View v, int keyCode, KeyEvent event) {
      if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
      {
      messsage = textField.getText().toString();
      textField.setText("");
      SendMessage sendMessageTask = new SendMessage();
      sendMessageTask.execute();

      return true;
      }
      return false;
      }
      });

      Delete
    6. Error:(39, 34) error: cannot find symbol class OnKeyListener

      Delete
    7. The error message is very general. It doesn't have much information. But i assume there should be a class path problem. Are all your packages obey Java naming conventions? Just Google, you will find an answer.

      Delete
  77. All I had to do was hit Alt+Enter, I'm sorry I'm still trying to learn. I do greatly appreciate your help. I didn't mention what all I was doing with this so I figured I'll tell you. I work at a cotton gin that handles module tags with barcodes. I handle the input side of the whole operation (16 trucks hauling cotton 12 hours a day/7 days a week). We needed a more error-free way of data collecting so I figured we can put tablets in the trucks with barcode scanners. Thanks to you, I am able to do that. I have the reconfigured client on the tablet wirelessly transmitting the number from the barcode to the server running on the scale house pc. All I have to do now is figure out how to tie in a com port to the server so when it receives the load number (barcode scanned) it will call the scales through serial to get the weight. Then I will need to figure out how to put those in a database then export them to a third party application. Seriously, you have no idea how much you have helped me. It works! This guy is a genius!

    ReplyDelete
    Replies
    1. Sounds great..!!! :) :)
      Really appreciate your feedback. It's a great pleasure to help the people like you. Actually this is the pleasure of writing and blogging. The feeling is awesome when the people find these things useful.
      Thanks again. Keep in touch with the blog. :)

      Delete
  78. hello! i tried running it...i installed the client program on my android device ..n i executed the server program on cmd on my laptop ..i changed the ip address accordingly ...but the messages aren't getting received by the server even if both programs are working properly...need help! thanks !

    ReplyDelete
    Replies
    1. How did you make the connection between the Android device and the lap top? That is the trickiest part here. How did you decide the IP address?

      Delete
    2. my mobile and my laptop are connected via same wifi n/w...actually,my laptop is using my phone's internet via hotspot....i found the ip using command ipconfig! btw thnx for replying so quickly...!

      Delete
    3. Great, you are in the right track. Hotsopt method is perfect. :)
      What you have got wrong is the IP address. ipconfig shows you the laptop IP address in the wifi network. But your hotspot network is a different network from the wifi network. That IP is not valid in the hotspot network.
      Your mobile connects to laptop through the hotspot network and your laptop connects to internet through the wifi network. Actually here you laptop acts like a router.
      The IP address you should use is the hotspot internet connection sharing IP address. If you are using a Windows OS, the default internet connection sharing IP is 192.168.137.1. Replace the IP address of your program with this IP.

      Delete
    4. no luck still...! :/ I put this IP instead of the one i found on ipconfig...no errors but still the same result...!thnk u!

      Delete
    5. What is your operating system? Can you find your hotspot internet sharing IP address?

      Delete
    6. windows..! nope...too many words...;p tell me the procedure to find it..! thank u!

      Delete
    7. hey never mind! it worked..! :p i couldn't really find the bug but i put IPv4 address from ipconfig again and this time it worked on my friend's cellphone...! i think my mobile has some n/w problems...! ;p thanx for the help!

      Delete
  79. Hello!

    I love you guy. You save my life (my master degree at least).
    I can now control my raspberry Robot with my android.

    Thanks a lot.

    ReplyDelete
  80. This comment has been removed by the author.

    ReplyDelete
  81. Hi
    I was created localhost http server and also created root folder (for access). In my localhost i can able to open the html files and jpg via browser. i want to open the media files (like audio and video). what should i do? In android jellybean video was opening fine but video forward was not working. In kitkat media files are not opening instead of its downloading. please suggest me any idea................ Thank you

    ReplyDelete
  82. I want both the client and server in android devices. So how should the server be written as an android app? Also, another question: if the client is an emulator and the server is an android device, they will be in different networks. Will that work too?

    ReplyDelete
    Replies
    1. 1. You can use an android device as the server. Whole code can't be presented in a comment. But in the following tutorial i have shown how the android client can receive the messages (not only sending the messages). You can follow this tutorial and understand how you can implement what you want.
      http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      2. That will work. You should create a network between the PC where the emulator running and the Android device. The simplest way is sharing the PC internet connection with Android device. Then it will create a wifi network (wifi hotspot). I have described how to do it in the following tutorial.
      http://lakjeewa.blogspot.com/2014/08/share-laptop-internet-connection-with.html

      Delete
  83. Hi!I'm Manouv , thank you for the code! it is working perfectly but i would like to enter the ip address manually in client app.
    Can you show me how can I do that please?

    ReplyDelete
  84. Hello!

    The tutorial is amazing! Thank you very much!
    I started doing the other way around. Server -. Client but it doen't work. i Cannot realize the connection, even though i consider it is ok, as the code is pretty much that. Do you have some tips about that or maybe another tutorial.
    I am kinda sure i am not that far from the solution, but for a few days I cannot understand the problem.

    ReplyDelete
    Replies
    1. Hej, is it maybe possible the server to reply to the client in this program using the same socket? The client send this message to the server, and the server should sent to the client that i tgot the message using the same server. Is that possible?

      Thank you in advance,
      Best Regards

      Delete
    2. just try the url https://github.com/bodeme/androidwebserver/ [make the some change and install the app click turn on and open mobile default browser type http://localhost:8080/ we will see]

      Delete
    3. In this[1] tutorial i have showed you how to create an application which has two way communication. I think all you can find your answers from this tutorial.

      [1] http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
  85. Hello Madhuranga. I would like to ask you a question about that. I am running the server in netbeans and I am trying to run the client in Android Studio but I am really new at this and I don't know how to do this exactly. I put the client code and I guess I have to edit the AndroidManifest and make a new xml file named activity_slimple_text_client in the same folder with AndroidManifest. Is that right? If this is what I am supposed to do, and I am doing it correctly, then I keep getting these 2 errors:
    1)Error:(16, 23) No resource found that matches the given name (at 'icon' with value '@drawable/ic_launcher').
    2)Error:Execution failed for task ':app:processDebugResources'.
    > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\Dimitris Vasileiadis\AppData\Local\Android\sdk\build-tools\21.1.2\aapt.exe'' finished with non-zero exit value 1

    If I am not supposed to follow these steps mentioned before, can you please help me with that? Thank you very much for your effort and time in advance! :)

    ReplyDelete
    Replies
    1. Hi Dimitris,
      Your starting steps are fine, you can do what you did. You can run the server on Netbeans and the client on Android Studio. But here the problem is, the client app cannot find the launcher icon. That is because of the way you created the client program. I assume error 2 is happening because of error 1. As you have explained it seems like you have created a new client program and copy paste the tutorial code. That is fine. But you may have to change the resource paths and other dependent variables.
      If you can import the whole client program to the Android studio (rather than creating new program), it would be easy since you are bigger. You can download the whole project form GitHub[1]. Download the program. You may have it a zip file. Unzip the content and import the project form Android studio.

      [1] https://github.com/lakjcomspace/AndroidTextClientServer/archive/master.zip

      Delete
  86. Hy Mr. Madhuranga,.. I'm running the client server on real device, and the server in my PC using eclipse. Android device is connected via usb cable to my PC. The problem is the client program always crash when execute this code line :
    client = new Socket("0.0.0.0", 4444);

    Btw, I have change the local server before to 127.0.0.1, but it gave the same result... How do I solve this problem Mr. Madhuranga.....??
    Thanks in advance...:-)

    ReplyDelete
  87. Ooooh... I got that 0.0.0.0 using this code
    System.out.println(serverSocket.getInetAddress().toString());... that's why I'm using 0.0.0.0 address at client socket... :-)

    ReplyDelete
  88. i have a wifi module that has ssid, pwd , ip address and port, i could connect to android mobile using ssid and pwd and it is connecting,using the ip address and port i could connect with module to get data from module. to test it i just downloaded tcp client apk and tested , i could receive data. but i want working source for this tcp client, iam making only one way communication, the module sends data after connected to it using ip address and port and what ever the data the module sends should be received in another label. i don't know to use your code for my requirement.pls help.

    ReplyDelete
  89. i have a wifi module that has ssid, pwd , ip address and port, i could connect to android mobile using ssid and pwd and it is connecting,using the ip address and port i could connect with module to get data from module. to test it i just downloaded tcp client apk and tested , i could receive data. but i want working source for this tcp client, iam making only one way communication, the module sends data after connected to it using ip address and port and what ever the data the module sends should be received in another label. i don't know to use your code for my requirement.pls help.

    ReplyDelete
  90. Thanks For Your valuable posting, it was very informative. Am working inErp Software Company In India

    ReplyDelete
  91. Really Nice Information,Thank You Very Much For Sharing.
    Web Designing Company

    ReplyDelete
  92. Thanks for the tutorial. We have a problem with sending messages to the server we have made. When we run the app and press the button to send a message, the server tells us that there is a connection but it hasn't received anything. Any potential fixes to this problem?

    ReplyDelete
    Replies
    1. How do you connect the app with the sever? Are you using an emulator environment or a real device?

      Delete
    2. We solved the problem, sorry about that. : )

      Delete
  93. Hi Lak J! I am wondering if I can create a server only in android that receives packets as follows:

    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;

    import android.os.Bundle;
    import android.app.Activity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Toast;


    public class ServerTest extends Activity implements Runnable{


    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_server_test);


    run();
    }

    @Override
    public void run() {

    Toast.makeText(this, "RIGHT BEFORE TRY", Toast.LENGTH_LONG).show();

    DatagramSocket socket = null;
    DatagramPacket packet;


    try {
    Toast.makeText(this, "IN THE TRY", Toast.LENGTH_LONG).show();
    socket = new DatagramSocket(9750,InetAddress.getLocalHost());
    byte[] buf = new byte[1024]; //buffer
    socket.setSoTimeout(100000);
    Toast.makeText(this, "Timeout is: " + socket.getSoTimeout(), Toast.LENGTH_LONG).show();

    while(true) {
    Toast.makeText(this, "IN THE WILD!", Toast.LENGTH_LONG).show();
    packet = new DatagramPacket(buf, buf.length);
    Toast.makeText(this, "PACKET SIZE IS: " + buf.length, Toast.LENGTH_LONG).show();

    try {
    socket.receive(packet);
    Toast.makeText(this, "GOT SOMETHING!", Toast.LENGTH_LONG).show();
    Toast.makeText(this, "SOCKET IS CLOSED!", Toast.LENGTH_LONG).show();
    }
    catch (Exception i) {
    // TODO Auto-generated catch block
    i.printStackTrace();
    Log.d("ServerTest", "run()",i);
    Toast.makeText(this, "DIDN'T GET IT HERE EITHER!", Toast.LENGTH_LONG).show();
    }
    byte[] result = packet.getData();
    System.arraycopy(packet.getData(), 0, result, 0, packet.getLength());
    String msg = new String(result);
    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    Toast.makeText(this, "END WHILE!", Toast.LENGTH_LONG).show();
    }

    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    Log.d("ServerTest", "run()",e);
    Toast.makeText(this, "DIDN'T GET IT!", Toast.LENGTH_LONG).show();

    }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_server_test, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
    return true;
    }

    return super.onOptionsItemSelected(item);
    }
    }


    ReplyDelete
    Replies
    1. When I run the code above the packets are never received and instead it goes to the exception and prints the toast "DIDN'T GET IT".

      Delete
  94. The tutorial was good and it worked fine for me......Please help me in another project related to this.....Requirement is to transfer the data without using internet

    ReplyDelete
  95. hey where to write the server.java?

    ReplyDelete
    Replies
    1. I don't get you question, can you please rephrase it with bit details?

      Delete
    2. i have created a project, my application name is client_server, and i have chosen blank activity named client, so i have client.java, androidmanifest.xml, activity_client.xml and strings.xml, now my question is where to write my server program(server.java).

      Or i have a server.cpp file, as shown below, but how can i modify it to listen the android client?

      #include
      #include
      #include
      #include
      #include
      #include
      #include
      #include

      using namespace std;

      int main()
      {
      int port = 22;
      int socket_handle = socket(AF_INET, SOCK_STREAM, 0);
      cout<= 0)
      {
      cout<<"Successful bind\n";
      cout<<"1"< 0)
      {
      cout<<buffer;
      send(socket_handle2, message, sizeof(message), 0);
      if(strncmp(buffer,"close", 5) == 0)
      {
      cout<<"Client asked me to close connection, closing\n";
      close(socket_handle2);
      break;
      }
      }
      else if (recv_ret == 0)
      {
      cout<<"Client closed connection\n";
      close(socket_handle2);
      break;
      }
      else
      {
      cout<<"Recv failed\n";
      }
      }
      } while(true);
      }
      else
      {
      cout<<"Bind failed"<<bind_ret<<"\n";
      }
      } while(true);
      cout<<"5"<<endl;
      }


      so any ideas can i get?

      Delete
    3. actually doing it in mac, android studio. the #inlcude command includes the following :
      , , , , , , ,


      also i am trying to connect android client to the server in pc(terminal) and the message recieved in server side should send a received message to the client. If you can help me in any ways, it would be of great help.

      thanks.

      Delete
    4. i created a project in android studio(in mac book pro), where the application name is client_server, and my blank activity name was client, so i had my client.java, androidmanifest.xml, activity_client.xml, so i have a doubt of where to write my server.java. i would also like to get to know that, the client should receive the received message from server, just to get the acknowledgement, basically trying to connect android client with the pc server. would be better to get ideas if you have understood my execution of the program.

      Delete
    5. all these replies are mine sent @ 29 june question

      Delete
    6. Hi Abhishek,
      Sorry for the delay.
      What you want to just understand is, Android client and Server is two different programs.
      You can run your Android client application on the emulator (Android studio) or Android device, while the Server program is running on your Mac.
      Android Client is a java program and you have written your Server in C++. That's fine, you can do it. Anyway, your question is where to put your server program. So the answer is it should be running in your computer so that your Android client app can create a connection.
      Hope this help :)

      Delete
    7. hey,
      can i get to know how to change my above code to a multithreaded server code?
      if you can please inform me. basically trying to connect multiple client to the server.

      Delete
    8. hey can you help me with that please?

      Delete
    9. can you help me with the above mentioned problem?

      Delete
    10. Sorry the delay again.
      You just have to do is, creating a thread for each connection when a client is connected. Message receiving part should be done inside the tread.
      I cannot put full code here in the comment. But if you search google for C++ thread programming, you will find bunch of examples.

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

    ReplyDelete
  97. Ho

    Thanks for the tutorial.

    I have a question. I run the client on the Genymotion emulator, before that I get the server started. It seems that the message was not sent. Should I change the client IP address to my IP address ?

    ReplyDelete
    Replies
    1. You should start the server before the client, that step is correct. But the rest is not clear for me in your question. A message will not be sent till you sent it by the client side.

      Delete
    2. Hi

      I opened the server first then run the client and then sent the message. At first it didn't work but I changed the IP address and the server received the message

      Delete
  98. HI madhuranga,
    i have an android application installed in my android device and XAMPP server running on my computer using apache and mysql. basically this is a chat app , server is up on my computer and i can able to chat between different android devices but the problem is i can able to chat only when the devices are connected to the same wifi network to which my server computer is connected, if one of the device is connected to other wifi network im not able to hit the server. so could u plz help me to solve this.
    thank you

    ReplyDelete
    Replies
    1. It is because your are running your server in local

      Delete
  99. This post is likeable, and your blog is very interesting, congratulations :-)

    ReplyDelete
  100. How would you suggest sending images from the device to the server and vice-versa??

    ReplyDelete
  101. Sir,
    I want to make server on android to send and receive messages.can you plz help in writing the code

    ReplyDelete
    Replies
    1. I assume you want your android device to receive data rather than sending. That's what you have mentioned as the server. If you, follow this tutorial.

      http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      This is a chat application. There you can see how the android device receives and sends data.

      Delete
  102. hello! this tutorial is very helpful.
    i want to make my chat app to communicate b/w 2 different n/w. any example you have?

    ReplyDelete
  103. Hi,

    I want to send message from server to client as received your message. What should i append to the above code to get that.

    ReplyDelete
    Replies
    1. Follow the bellow tutorial. It's a android client server chat application. There you will learn how to do what you want. :)
      http://lakjeewa.blogspot.com/2015/01/android-client-server-chat-application.html

      Delete
    2. Thanks a lot .. It is working perfectly ..
      Now if i want to create new intent in client after receiving the message how can i do it and how can i pass socket , inputstream , outputstream to new intent?

      Delete
    3. Sorry friend, i can't get your question. Can you please rephrase it.

      Delete
  104. will it work inter network. if the client and server are in different network ?

    ReplyDelete
    Replies
    1. Yes, it should. But you should configure and connect devices properly.

      Delete
  105. Finaly! Exactly what i was looking for... thank you

    ReplyDelete
  106. public class MainActivity extends Activity {
    EditText editTextout;
    TextView textViewIn;
    DataOutputStream dout;
    DataInputStream din;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editTextout=(EditText)findViewById(R.id.editText1);
    textViewIn=(TextView)findViewById(R.id.textView1);
    String str2=textViewIn.getText().toString();
    editTextout.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keycode, KeyEvent event){
    String message="";
    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keycode == KeyEvent.KEYCODE_ENTER))
    {
    message = editTextout.getText().toString();
    editTextout.setText("");
    SendMessage sendMessageTask = new SendMessage();
    sendMessageTask.execute();

    return true;
    }
    return false;
    }
    });
    }
    private class SendMessage extends AsyncTask{

    @Override
    protected Void doInBackground(Void... arg0) {
    // TODO Auto-generated method stub
    Socket s = null;
    try {
    s = new Socket("192.168.45.1",5555);
    } catch (UnknownHostException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    } catch (IOException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
    }
    try {
    DataInputStream din=new DataInputStream(s.getInputStream());
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    try {
    DataOutputStream dout=new DataOutputStream(s.getOutputStream());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String message="";
    TextView textView=textViewIn;
    String str2="";
    while(!message.equals("stop")){
    try {
    message=br.readLine();
    dout.writeUTF(message);
    dout.flush();
    str2=din.readUTF();
    textViewIn.setText(str2);
    dout.close();
    s.close();
    }
    catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    return null;
    }

    }
    get the server message into textview and also our message display on text view. below i put the java code like that samethings i want to in android...

    ReplyDelete
  107. Client.java

    import java.net.*;
    import java.io.*;
    class Client{
    public static void main(String args[])throws Exception{
    Socket s=new Socket("localhost",3333);
    DataInputStream din=new DataInputStream(s.getInputStream());
    DataOutputStream dout=new DataOutputStream(s.getOutputStream());
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    String str="",str2="";
    while(!str.equals("stop")){
    str=br.readLine();
    dout.writeUTF(str);
    dout.flush();
    str2=din.readUTF();
    System.out.println("Server says: "+str2);
    }

    dout.close();
    s.close();
    }}


    Server.java

    import java.net.*;
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    class Server{

    public static void main(String args[])throws Exception{

    ServerSocket ss=new ServerSocket(3333);
    Socket s=ss.accept();
    DataInputStream din=new DataInputStream(s.getInputStream());
    DataOutputStream dout=new DataOutputStream(s.getOutputStream());
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    String str="",str2="";
    while(!str.equals("stop")){
    str=din.readUTF();
    System.out.println("client says: "+str);
    str2=br.readLine();
    dout.writeUTF(str2);
    dout.flush();
    }
    din.close();
    s.close();
    ss.close();
    }}

    ReplyDelete
  108. Nice article! Thank you! :D

    ReplyDelete