Let’s make a client app which will communicate with java client using Java Socket API. First we are going to design a UI in which we provide user to given Host Ip and Host Port and message to send to the client.
Layout.xml
<RelativeLayout 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:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.rizem.clinetserver.MainActivity” >
<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:orientation=”vertical” >
<LinearLayout
android:id=”@+id/detail_layout”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” >
<EditText
android:id=”@+id/hostIp”
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”1″
android:ems=”10″
android:hint=”@string/hostiptxt”
android:inputType=”text”/>
<EditText
android:id=”@+id/hostPort”
android:layout_width=”97dp”
android:layout_height=”wrap_content”
android:layout_weight=”1″
android:ems=”10″
android:hint=”@string/hostposttxt”
android:inputType=”number”/>
</LinearLayout>
<EditText
android:id=”@+id/requestTxt”
android:layout_width=”match_parent”
android:layout_height=”150dp”
android:ems=”10″
android:hint=”@string/requsetTxt”
android:inputType=”text|textPostalAddress” >
<requestFocus />
</EditText>
<LinearLayout
android:id=”@+id/controllayout”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” >
<Button
android:id=”@+id/btnSend”
style=”?android:attr/buttonStyleSmall”
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”1″
android:text=”@string/btnSendTxt” />
</LinearLayout>
<EditText
android:id=”@+id/responseTxT”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:ems=”10″
android:inputType=”textMultiLine”
android:text=”@string/responseTxt” />
</LinearLayout>
</RelativeLayout>
Now we start with our client class which used to communicate with java server using AsyncTask API of Android.
Client Utility Class
public class Client {
private final String TAG = “Client”;
private String response = “NO RESPONSE”;
public String sendDataToServer (String hostIP, String port, String Data) {
try {
SocketTask task = new SocketTask();
task.execute(“SendData”, hostIP, port, Data);
response = task.get();
}
catch (InterruptedException | ExecutionException e) {
Log.e(TAG,”Error Occurred :” + e.getMessage());
}
return response;
}
public class SocketTask extends AsyncTask<String, Void, String> {
String result = “NO_RESULT”;
@Override
protected String doInBackground (String… params) {
WebServiceTask openSocketTask = new WebServiceTask();
if (params[0].equals(“SendData”)) {
result = openSocketTask.sendAndGetData(params[1], Integer.valueOf(params[2]),
params[3]);
}
return result;
}
@Override
protected void onPostExecute (String result) {
super.onPostExecute(result);
}
}
private class WebServiceTask {
String response = “”;
Socket socket = null;
public String sendAndGetData (String hostIp, int hostPort, String data) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
String response = “”;
try {
socket = new Socket(hostIp, hostPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
if (data != null) {
dataOutputStream.writeUTF(data);
}
response = dataInputStream.readUTF();
System.out.println(“Response From Java APP ” + response);
}
catch (UnknownHostException e) {
Log.e(TAG,”Error Occurred :” + e.getMessage());
response = “UnknownHostException: ” + e.toString();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred :” + e.getMessage());
response = “IOException: ” + e.toString();
}
finally {
if (socket != null) {
try {
socket.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred :” + e.getMessage());
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred :” + e.getMessage());
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred :” + e.getMessage());
}
}
}
return response;
}}
Now this class contains a sub class which extends AsyncTask class to perform network activity in background thread because android dose not allowed to perform a network activity in ui thread. Lets move on to Main Activity class which execute all the operations
MainActivity
public class MainActivity extends Activity {
private final String TAG = “ClientActivity”;
private EditText hostIp = null;
private EditText port = null;
private EditText requestMessage = null;
private EditText responseMessage = null;
private Button send = null;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hostIp = (EditText) findViewById(R.id.hostIp);
port = (EditText) findViewById(R.id.hostPort);
requestMessage = (EditText) findViewById(R.id.requestTxt);
responseMessage = (EditText) findViewById(R.id.responseTxT);
send = (Button) findViewById(R.id.btnSend);
final String hostIP = hostIp.getText().toString();
final String hostPort = port.getText().toString();
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
String data = requestMessage.getText().toString();
Client client = new Client();
String result = client.sendDataToServer(hostIP, hostPort, data);
responseMessage.setText(result);
}
});
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive
// Intents
// with actions named “custom-event-name”.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter(“custom-event-name”));
}
// Our handler for received Intents. This will be called whenever an
// Intent
// with an action named “custom-event-name” is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive (Context context,Intent intent) {
String message = intent.getStringExtra(“message”);
responseMessage.setText(message);
}
};
}
Now lets move to second app which contains server class:
public class ServerActivity extends Activity {
TextView info , infoip , msg;
private static final String TAG =”ServerActivity”;
String message = “”;
ServerSocket serverSocket;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_server);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
@Override
protected void onDestroy () {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred while starting server : ” + e.getMessage());
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
@Override
public void run () {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
ServerActivity.this.runOnUiThread(new Runnable() {
@Override
public void run () {
info.setText(“Server Status: ” + serverSocket.getLocalPort());
}
});
//Keep running the server
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String messageFromClient = “”;
// If no message sent from client, this code will block
// the program
messageFromClient = dataInputStream.readUTF();
count++;
message += “#” + count + ” from ” + socket.getInetAddress() + “:”
+ socket.getPort() + “\n” + “Msg from client: ” + messageFromClient
+ “\n”;
ServerActivity.this.runOnUiThread(new Runnable() {
@Override
public void run () {
msg.setText(message);
}
});
String msgReply = “Hello from Android, you are #” + count;
dataOutputStream.writeUTF(msgReply);
}
}
catch (IOException e) {
Log.e(TAG,”Error Occurred : ” + e.getMessage());
final String errMsg = e.toString();
ServerActivity.this.runOnUiThread(new Runnable() {
@Override
public void run () {
msg.setText(errMsg);
}
});
}
finally {
if (socket != null) {
try {
socket.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred : ” + e.getMessage());
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred : ” + e.getMessage());
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
}
catch (IOException e) {
Log.e(TAG,”Error Occurred : ” + e.getMessage());
}
}
}
}
}
private String getIpAddress () {
String ip = “”;
try {
Enumeration enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += “SiteLocalAddress: ” + inetAddress.getHostAddress() + “\n”;
}
}
}
}
catch (SocketException e) {
Log.e(TAG,”Error Occurred : ” + e.getMessage());
ip += “Something Wrong! ” + e.toString() + “\n”;
}
return ip;
}
}