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.

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.

Other supporting components

Implementation of activity_main.xml file.

AndroidManifest.xml

We will need permission INTERNET to create Sockets. Don’t forget to include that permission in your 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...

Leave a Reply

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