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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?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