Android Client-Server Using Sockets – Client Implementation

In this Android Client-Server Using Sockets post we will be focusing on client side implementation. We have covered Server side implementation in our previous post “Android Client-Server Using Sockets – Server Implementation”

Implementation Details

In this tutorial we will be using java Sockets to achieve our server-client communication. In client user will fill IP and port details in EditText and then it will press connect. Server will replay to the query. For implementation of Client we will be extending AsyncTask . Socket is created using IP and port detail and replay from server is decoded.

 

[su_button url=”https://github.com/androidsrc/SocketClient” target=”blank” style=”stroked” background=”#51d461″ color=”#ffffff” size=”6″ center=”yes” radius=”0″ icon=”icon: arrow-circle-o-down”]Download Full Source Code[/su_button]

 

Note : This tutorial is based on Eclipse 4.3, Java 1.6 and Android 4.4.2.

Client Implementation

Implementing Client.java

This class contain all the implementation of client. This class is created by extending AsyncTask so that multitasking will be easy. We create a socket using IP and port detail which was provided by the user. Next getInputStream() is called on created socket to get InputStream so as to read data from this socket. Connection is blocked untill no data is read. This all must be done in try catch block so that exceptions must be handled.

package com.androidsrc.client;

import android.os.AsyncTask;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client extends AsyncTask<Void, Void, Void> {

    String dstAddress;
    int dstPort;
    String response = "";
    TextView textResponse;

    Client(String addr, int port, TextView textResponse) {
        dstAddress = addr;
        dstPort = port;
        this.textResponse = textResponse;
    }

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

        Socket socket = null;

        try {
            socket = new Socket(dstAddress, dstPort);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                    1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            InputStream inputStream = socket.getInputStream();

			/*
             * notice: inputStream.read() will block if no data return
			 */
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    @Override
    protected void onPostExecute(Void result) {
        textResponse.setText(response);
        super.onPostExecute(result);
    }

}

Implementation of MainActivity.java class

The usage of client class is very simple. Just create a object of Client class and pass IP and port of server and response TextView. Here is what MainActivity.java looks like.

package com.androidsrc.client;

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

public class MainActivity extends Activity {

    TextView response;
    EditText editTextAddress, editTextPort;
    Button buttonConnect, buttonClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextAddress = (EditText) findViewById(R.id.addressEditText);
        editTextPort = (EditText) findViewById(R.id.portEditText);
        buttonConnect = (Button) findViewById(R.id.connectButton);
        buttonClear = (Button) findViewById(R.id.clearButton);
        response = (TextView) findViewById(R.id.responseTextView);

        buttonConnect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Client myClient = new Client(editTextAddress.getText()
                        .toString(), Integer.parseInt(editTextPort
                        .getText().toString()), response);
                myClient.execute();
            }
        });

        buttonClear.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                response.setText("");
            }
        });
    }
}

Other supporting components

Implementation of activity_main.xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:autoLink="web"
        android:text="http://androidSRC.net/"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/addressEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Server ip address" />

    <EditText
        android:id="@+id/portEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Server port number" />

    <Button
        android:id="@+id/connectButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Connect..." />

    <Button
        android:id="@+id/clearButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Clear" />

    <TextView
        android:id="@+id/responseTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

 AndroidManifest.xml

We will need permission INTERNET to create Sockets. Don’t forget to include that permission in your manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidsrc.client"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Testing the application

To test this application install it on android device and install client on other device. Both device should be connected to same wifi network. Now just add IP address and port to client and click connect. Server will replay with a message to client. Thanks

Any further queries or custom tutorial please comment or mail us at androidsrcdotnet@gmail.com

GuRu

Technology enthusiast. Loves to tinker with things. Always trying to create something wonderful using technology. Loves coding for Android, Raspberry pi, Arduino , Opencv and much more.

You may also like...

25 Responses

  1. Denis says:

    thanks for tutorial!
    why both device should be connected to same wifi network? how can I connect devices via 3G?

  2. Josh says:

    nice tutorial.
    will this work if a pc running .net asynchronous server socket is used instead of the android server?

  3. Abhinav Bhargav says:

    hi,

    I would like to know one thing(client and server are 2 different projects/apps)

    line1 outputStream = hostThreadSocket.getOutputStream();

    line2 PrintStream printStream = new PrintStream(outputStream);

    line3 printStream.print(msgReply);

    line4 printStream.close();

    if line3 printstream.print(msgReply) which is server side code is sending some useful message to client.

    Now if i want to use that message in my client program, how can i ?

    How can i save that message in client project in a variable or anything else? please help.

  4. Roel says:

    I can’t help it but I can’t take examples serious with Eclipse “// TODO Auto-generated catch block” parts.

  5. nikhil sani says:

    which IP address to enter ?
    not able to connect when i entered IP address which is showing in Server app

  6. manoj says:

    hi sir,good tutorial
    how to File transfer via Socket, between Android devices, is there any solution
    please give me answer, how to solve these problem

  7. Darren Close says:

    Hi there, this tutorial has helped me so much so thank you. I am trying to write an app that when it receives a message via the Socket which contains a specific phrase e.g. “SEND” it will invoke some other code (mainly send a text). Can you suggest where I put this code as I need the app to continually listen to the incoming messes and then invoke this new code when the condition is met.

  8. Ishan Mourya says:

    Can we use this for Making a chatting app….means connect 2 devices using server and client and then chat between them

  9. Conrad Addo says:

    How do I decide the port number?

  10. Yeac says:

    Is it possible to have more than one client connection??

  11. Aruna Gamage says:

    How do I decide the port number?

  1. December 12, 2015

    […] Kaynak: Android Client-Server Using Sockets – Client Implementation […]

  2. February 2, 2017

    […] on server side implementation. We have covered Client side implementation in our previous post “Android Client-Server Using Sockets – Client Implementation” Android has very vast set of libraries so that users can implement innovative ideas with provided […]

  3. February 24, 2017

    […] have followed this tutorial to get the basic […]

Leave a Reply

Your email address will not be published. Required fields are marked *