Showing posts with label Android code sample: Networking. Show all posts
Showing posts with label Android code sample: Networking. Show all posts

Node.js server communicate with Android client

This example create TCP server with Node.js using net module, run on Raspberry Pi.


For the server side implemented in Node.js, refer to my another blog Hello Raspberry Pi: Create TCP server using Node,js with net module, run on Raspberry Pi, connected with Android.

For the client side, refer to my former post: Android Server/Client example - client side using Socket.

Android Server/Client example - client side using Socket

It's the client side implementation of our Server/Client example, the server side is listed in last post "server side using ServerSocket".

Android client side using Socket
Android client side using Socket

package com.example.androidclient;

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
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 textResponse;
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.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);

buttonConnect.setOnClickListener(buttonConnectOnClickListener);

buttonClear.setOnClickListener(new OnClickListener(){

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

OnClickListener buttonConnectOnClickListener =
new OnClickListener(){

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

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

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

MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}

@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 null;
}

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

}

}

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />
<EditText
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstAddress" />
<EditText
android:id="@+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstPort" />
<Button
android:id="@+id/connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect..."/>
<Button
android:id="@+id/clear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear"/>
<TextView
android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>

Remark: uses-permission of "android.permission.INTERNET" is needed.

download filesDownload the files.



Related:
- Node.js server communicate with Android client

Android Server/Client example - server side using ServerSocket

It's the server side implementation of our Server/Client example, the client side is listed in next post "client side using Socket".

Android Server using ServerSocket
Android Server using ServerSocket
In this server side implementation, it will list its own IP address when program start. And run in background thread, start a ServerSocket and wait at serverSocket.accept(). Once any request received, it return a message to client side.

package com.example.androidserversocket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

private class SocketServerThread extends Thread {

static final int SocketServerPORT = 8080;
int count = 0;

@Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});

while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
msg.setText(message);
}
});

SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();

}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

private class SocketServerReplyThread extends Thread {

private Socket hostThreadSocket;
int cnt;

SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}

@Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;

try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();

message += "replayed: " + msgReply + "\n";

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
msg.setText(message);
}
});

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
msg.setText(message);
}
});
}

}

private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();

if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}

}

}

} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}

return ip;
}
}

<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"
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=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

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

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >

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

</LinearLayout>

Remark: uses-permission of "android.permission.INTERNET" is needed.

download filesDownload the files.

Get my IP Address

It's a example to list IP address of Android device.

my IP Address
my IP Address

package com.example.androidmyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView info;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView)findViewById(R.id.info);

info.setText(getIpAddress());
//info.setText(getLocalIpAddress());
}

private String getIpAddress(){
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces =
NetworkInterface.getNetworkInterfaces();
while(enumNetworkInterfaces.hasMoreElements()){
NetworkInterface networkInterface =
enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress =
networkInterface.getInetAddresses();
while(enumInetAddress.hasMoreElements()){
InetAddress inetAddress = enumInetAddress.nextElement();

String ipAddress = "";
if(inetAddress.isLoopbackAddress()){
ipAddress = "LoopbackAddress: ";
}else if(inetAddress.isSiteLocalAddress()){
ipAddress = "SiteLocalAddress: ";
}else if(inetAddress.isLinkLocalAddress()){
ipAddress = "LinkLocalAddress: ";
}else if(inetAddress.isMulticastAddress()){
ipAddress = "MulticastAddress: ";
}
ip += ipAddress + inetAddress.getHostAddress() + "\n";
}

}

} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}

return ip;
}

}

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold" />

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

</LinearLayout>

Remark: <uses-permission android:name="android.permission.INTERNET"/> is needed in AndroidManifest.xml.

download filesDownload the files.