Madhuranga Lakjeewa's Cyberspace


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

SlimpleClientActivity.java

/*
 * This is a simple Android mobile client
 * This application read any string messege typed on the text field and 
 * send it to the server when the Send button is pressed
 * Author by Lak J Comspace
 */

package lakj.comspace.simpleclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SimpleClientActivity extends Activity {

 private Socket client;
 private PrintWriter printwriter;
 private EditText textField;
 private Button button;
 private String messsage;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  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

    try {

     client = new Socket("10.0.2.2", 4444);  //connect to server
     printwriter = new PrintWriter(client.getOutputStream(),true);
     printwriter.write(messsage);  //write the message to output stream

     printwriter.flush();
     printwriter.close();
     client.close();   //closing the connection

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

 }
}

main.xml



    

        

    


    

AndroidManifest.xml



    
    

    
        
            
                

                
            
        
    



Server Side Application

main.java

/*
 * This is a simple server application
 * This server receive a string message from the Android mobile phone
 * and show it on the console.
 * Author by Lak J Comspace
 */
package simpleserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    public static void main(String[] args) {

        try {
            serverSocket = new ServerSocket(4444);  //Server socket

        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
        }

        System.out.println("Server started. Listening to the port 4444");

        while (true) {
            try {

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

                System.out.println(message);
                inputStreamReader.close();
                clientSocket.close();

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

    }
}

78 comments:

Akemi Kobayashi said...

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

日本NCH

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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

John Laura said...

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

Takumi Yano said...

This is like my fourth time stopping over your Blog. Normally, I do not make comments on website, but I have to mention that this post really pushed me to do so. Really great post .

ケムサーチ

jack said...

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

Mark Tull said...

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

antibacterial wipes

raja reddy said...

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

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

Phil Burgham said...

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

BA Dissertation said...

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

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

Yeah BA, Exactly that.You got the point.

Noah OWENS said...

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

Hong said...

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.

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

ozu said...

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.

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

Trần Tân said...

thank you very much !

zeen said...

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

zeen said...

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

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

Anonymous said...

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

Anonymous said...

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 :-(

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

zeen said...

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

Mark Connolly said...

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

Anonymous said...

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

princy matlani said...

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

Karishma said...

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

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

Anonymous said...

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.

Anonymous said...

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

Kashyap Das said...

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

Mahendra Pratap said...

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

Anonymous said...

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

Sridhar Muruganandham said...

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

Anonymous said...

Luvv u man!!

Anonymous said...

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?

hari.s said...

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

Jung Hur said...

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

mith said...

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

Phil said...

Won't work for me :/ Client crashes

Anonymous said...

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?

Anonymous said...

Added AsyncTask and the application worked ! Thanks

Htet Nandar Toe said...

Thanks you very very very.................much!

Agniv said...

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

Anonymous said...

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?

Anonymous said...

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

Hassan Jaffrani said...

no result
nothing happening
please help

Anonymous said...

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

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

Anonymous said...

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

regards
Krishh

Vishnu Nagaraj said...

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

Anonymous said...

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

Mayur Nalwaya said...

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

Tibor Szelitzky said...

Hi

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

Muhammad Usman said...

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

Anonymous said...

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!

Roshani Sutey said...

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

Muhammad Shehzad Arshad said...

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

SARWAR said...

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

ashish sahu said...

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

Anonymous said...

can we connect android phone as server client via bluetooth

Serveh Karimi said...

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

Anonymous said...

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.

ajay said...

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

Anonymous said...

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

ADWAIT said...

i get Force Close error always

shivam jaiswal said...

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

Bunyod Bobojonov said...

how do i implement with java.nio?

fledging said...

where to write server side coding in this app?

pranav said...

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

Rohit Agrawal said...

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

Wayan Giri said...

Can you make specific chat apps

Anonymous said...

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

Mothusi Molorane said...

I got this error FATAL EXCEPTION: main

Rahul Tharwani said...

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

Anonymous said...

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?

Madhuranga Lakjeewa (මධුරංග ලක්ජීව) said...

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.

Shreya Gupta said...

what if androidmanifestxml is not there?

Post a Comment

 
Design by Wordpress Theme | Bloggerized by Free Blogger Templates | coupon codes