This is a simple Android chat application which communicate with a Java server program. This tutorial will help you to understand socket programming in Android which sends information both ways.
To run this application, first execute the server program. You can run this application in your PC.
Then execute the client program. You can use your Android emulator or your Android device. If you are using Android emulator you can use IP address 10.0.2.2 to connect your sever which is running in the same computer. But if you are using an Android device you may have to change the IP address in the client app code according to your network configuration.
Once you execute the client app, the chat window will be opened in the server program. Type the message on the chat box and press "Send" button. The message will be appeared in the other end.
Android Chat App |
Server Program |
Following are the source codes of the main components of both programs.
Android Chat Application
Server Program
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/AndroidChatClientServer.git
Git-Hub Repository URL: https://github.com/lakjcomspace/AndroidChatClientServer
Download as a Zip: https://github.com/lakjcomspace/AndroidChatClientServer/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.
I executed the application but i wanted to know if i received a string from the client and i assigned it to a variable and wanted to apply a function on that variable and then send it back. Is it gonna be easy to do that. I already asigned the string received to a variable in the "simplechatserver.Receiver" class but i don't know how to use that variable in the Sender class.
ReplyDeleteYes its easy, you can do that.
DeleteYou should do this in the sever program. Both "Receiver" and "Seder" are initialized in the "ChatWindow" class. Therefore the common place for both "Receiver" and "Seder" is "ChatWindow" class. Keep global references (variables) to both "Receiver" and "Seder". Create method inside "ChatWindow" which does your particular string operation and call receiver to send the message. Pass a reference to ChatWindow class when you create the Receiver class. You should change the Receiver class constructor to do that. From that you may be able to call your particular method when the Receiver receives a message. You should call that method after line number 50 of Receiver.java class.
Hope you can understand my guideline. :)
and actually what i want to do is per example : i send a number ( ex : 17 ) to the server and the server sum this number with another number and return the result to the android client.
DeleteI kinda don't fully understand what you wrote.
String string = message;
DeleteString[] parts = string.split("-");
String part1 = parts[0];
String part2 = parts[1];
i added these lines after "message = bufferedReader.readLine(); // Read the chat message. "
so that i split the string that i am receiving.
than i want to apply a method to these strings example func ( part1,part2,number1,number2)
and then send the result back to the client.
I can present whole answer from a comment, but i will brief and highlight the most important places you should change. Following are the ChatWindow and Receiver classes. This will help you to understand the above comment.
Delete-----------------------------------------------------------------------------------------------------------------------------
public class ChatWindow{
private void initSenderAndReceiver(final Socket clientSocket) {
// Using this key word you can pass the reference to ChatWindow to the Receiver.
Receiver receiver = new Receiver(clientSocket, chatView, this);
}
public void yourMethod(String message){
// do here whatever you want.
}
------------------------------------------------------------------------------------------------------------------------------------
public class Receiver{
private ChatWindow chatWindow;
public Receiver(Socket clientSocket, JTextArea chatViewParam,ChatWindow chatWindowParam) {
chatWindow = chatWindowParam;
}
@Override
public void run() {
// Here inside the while loop you can do the following.
chatWindow.yourMethod(message);
}
}
I understood this part, but you didn't mention how to send the result of the method back to the android client.
DeleteI am sorry for asking these much of questions, but i want to understand.
In my first comment i told you to keep global variables for "Sender" and "Receiver" in the ChatWindow class. Let's say Sender's global variable is "sender" (private Sender sender;). You are calling yourMethod(String message) which is in the ChatWindow class. So you can simply call the sender.sendMessage(String message) method inside youMethod.
DeleteYour method will look like:
public void yourMethod(String message){
// Do whatever you want here. Lets say you are producing
// a string called "yourString" after all your manipulations on "message".
// Then add the following line to this method.
sender.sendMessage(yourString);
}
Ok, Thanks a lot, now i understood.
DeleteHi,
ReplyDeletei got output from android emulator with PC.
but How can i Communicate with android device with PC through wifi.
can you give your Reply?
Hi,
ReplyDeleteIs it possible the client connect to the server through internet instead of local network?
Yes, but your server should be publicly accessible. That means, you should host your server program in a real web server.
DeleteHi Madhu,
ReplyDeleteThe client will lost connection with the server if stop chatting for few minutes, any idea on this or preventive can be done?
This website was... how do I say it? Relevant!
ReplyDelete! Finally I have found something that helped me. Appreciate
it!
Feel free to visit my weblog www.freshappz.com
I need your help to break out some functionality in the client side.
ReplyDeleteRight now when the app is started, the socket is created and listens for incoming server messages.
I would like to connect creation of the socket to a button so when I click on the connectButton then socket is being created in the background
Cheers
Masoud
Hi Masoud,
DeleteSorry for the delay. It is possible, you can simply do it. I will explain.
You know that, now the socket is created when the app is started. That is true. Actually the onCreate() method (line 40) is called when the application is started. There a ChatOperator object is created and chatOperator.execute() method create the socket.
Create a new button (like in line 44) for your "Connect" button. Then add the following lines of code instead of lines 47 and 48.
boolean isConnectButtonClicked = false;
connectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(! isConnectButtonClicked ){
isConnectButtonClicked = true;
ChatOperator chatOperator = new ChatOperator();
chatOperator.execute();
}
});
What the above few lines does is, a click action listener is bound so that the socket creation happens when the button is clicked. isConnectButtonClicked boolean variable will keep the status of connect button clicked status. The user should only be able to connect once, otherwise the the socket will create again and again at the each time the user click the button.
Hope you understand my explanation. If not, don't hesitate to keep asking the questions. :)
Thanks, it worked like a charm.
DeleteHowever I have a disconnect button as well. Once I click on that, it releases the socket and enable the connect button. As the connect button now is inside the Oncreate procedure, it will never be called for a second time when I click on it. You can find the code here:
http://www.testlead.se/android/MainActivity.java
This tutorial will help you to understand socket programming in Android which sends information both ways. Cell Phone Tracker Online For Free
ReplyDeletemy client app is saying "unfortunately app has stoped working" when i installed on my phone.. could u help me plz?
ReplyDeletethank u!
The error message you have mentioned is so general. That is not enough to understand the issue. Can you find the server responses or error log entries?
DeleteThis post is likeable, and your blog is very interesting, congratulations :-)
ReplyDeleteThank you... :)
DeleteHi Madhu
ReplyDeleteI want to have server on another android device not on the PC. What should I change in server code?
Thanks
You can do it. You just want to create an android app which does the server functionality. You can use the same code handle server side functionality. But creating the network between the android devices is the trickiest part. :)
DeleteHi Madhu
DeleteI have tried a lot trying to put server on android device but it was difficult.Can you plz help me
I am new in android and java Would you please change code to android?
ReplyDeleteIt makes so many errors on changing code to android
ReplyDeleteCan we save the chat? If so please let me know
ReplyDeleteYes, you can be done. But in the tutorial i haven't implement it. If you close the app, every chat messages will be lost.
Deletecan we put the server program in android
ReplyDeleteHi, Can we make one to one chatting through this code?. If yes can you please suggest how we can achieve this.
ReplyDeleteYes,This is already an one to one chat since the server is accepting only one chat client. But if you want advance options like authentication, you need to implement it. :)
DeleteHi Lakjeewa,
ReplyDeleteUsing above code how we can do one(server) to many(client) communication.
Generally we aware of that Chat concept. how to achieve using code.
Ex. Sanjay(client) send request and Shyam(client) send a request
Now Server accept both request then Server how to identify which client have requested. so response only them.
Your requirement is bit of advance than the tutorial.
DeleteIf you go through the server program you will see that i am creating only one thread for receiver(Client). Just look at line #87 in ChatWindow class. If you are going to have more client you may have to create threads for each.
Thanks for you suggestion but just i want to know a little bit idea/example.
DeleteIf i will be implement by using multi thread it will be possible to multiple client communicate with the Server at time simultaneously. Could you please guide me or suggest/idea/ or provide me the code how to implement it.
Thanks
Hi ,
ReplyDeleteCan we write and read cookies in Android WebView. Example :
1. Any webpage open in WebView Intent in application.and set cookies in device. now that stored cookies. can we read from another android application which is another application.(Cookies communicate within two application one application is doing write cookies and second application read that stored cookies.)
is it possible to achieve it. if yes pls help..
Hello,
ReplyDeleteI am getting NullPointerException at Client side. Here is my logcat view that shows exception in detail. Please Help me out for this.
E/AndroidRuntime(12635): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(12635): at android.os.AsyncTask$3.done(AsyncTask.java:304)
E/AndroidRuntime(12635): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
E/AndroidRuntime(12635): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
E/AndroidRuntime(12635): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
E/AndroidRuntime(12635): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
E/AndroidRuntime(12635): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/AndroidRuntime(12635): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/AndroidRuntime(12635): at java.lang.Thread.run(Thread.java:818)
E/AndroidRuntime(12635): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.BufferedReader.ready()' on a null object reference
E/AndroidRuntime(12635): at com.example.demochatappclient.MainActivity$Receiver.doInBackground(MainActivity.java:110)
E/AndroidRuntime(12635): at com.example.demochatappclient.MainActivity$Receiver.doInBackground(MainActivity.java:1)
E/AndroidRuntime(12635): at android.os.AsyncTask$2.call(AsyncTask.java:292)
E/AndroidRuntime(12635): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
how to run this project on android studio please help me
ReplyDeleteHow many threads are running on server? Could you please explain them.
ReplyDeleteis it possible to communicate between pc to pc,mobile to pc,pc to mobile and mobile to mobile through this app?
ReplyDeleteThis particular scenario has been implemented to communicate between mobile and pc. But you can change this program to cater all scenarios you have mentioned.
DeleteThank you.
ReplyDeleteIt's been a lot of help in solving this problem.