I want to transfer a file between two devices, a server and a client .. I have a little problem on the client side.
I got this error in logcat:
java.lang.ArrayIndexOutOfBoundsException: length=1024; regionStart=0; regionLength=-1
please if my codes are wrong tell me. I want to make an app and its 4 days i am working on transfering. it get to me awful. please help
this is the client:
package com.example.test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Environment;
public class MainActivity extends ActionBarActivity {
EditText editTextAddress;
Button buttonConnect;
TextView textPort;
static final int SocketServerPORT = 8000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
textPort = (TextView) findViewById(R.id.port);
textPort.setText("port: " + SocketServerPORT);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
ClientRxThread clientRxThread =
new ClientRxThread(
editTextAddress.getText().toString(),
SocketServerPORT);
clientRxThread.start();
}});
}
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(
Environment.getExternalStorageDirectory(),
"input.jpg");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
"Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
client xml:
<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="com.example.androidsocketfiletransferclient.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="File Transfer Client"
android:textStyle="bold" />
<EditText
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dstAddress" />
<TextView
android:id="#+id/port"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect..." />
client manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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>
server :
package com.example.testserverandroid;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
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.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
TextView infoIp, infoPort;
static final int SocketServerPORT = 8000;
ServerSocket serverSocket;
ServerSocketThread serverSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
infoIp.setText(getIpAddress());
serverSocketThread = new ServerSocketThread();
serverSocketThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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;
}
public class ServerSocketThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory(),
"test.txt");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
socket.close();
final String sentMsg = "File sent to: "
+ socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, sentMsg,
Toast.LENGTH_LONG).show();
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
server manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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>
In your client, when you are reading from the input stream, the number of bytes read will be -1 if you are already at the end of the stream. This is described in the documentation for InputStream.
The ArrayIndexOutOfBoundsException exception occurs when this statement executes and bytesRead is -1.
bos.write(bytes, 0, bytesRead);
You need to restructure your client code that reads the input stream to check for end-of-stream.
Replace this:
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
With this:
int bytesRead;
while ((bytesRead = is.read(bytes)) > 0) {
bos.write(bytes, 0, bytesRead);
}
Related
I am using SimpleBluetoothLibrary to access my bluetooth printer.now i can search available devices,select bluetooth printer from the list,connect to the printer.those parts are done.but i don't know how to send data to the printer for print job.this is onDeviceConnected method.i've got device address from it.but i want to send data to printer.
#Override
public void onDeviceConnected(BluetoothDevice device) {
//a device is connected so you can now send stuff to it
mTxt.setText("Connection Status:Connected:" + device.getAddress());
Log.d("Mac_Address", device.getAddress());
}
There is a simple example for sending data from Bluetooth.I hope it helps you.
MainActivity.java
package com.example.bluetoothprinter;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// will show the statuses
TextView myLabel;
// will enable user to enter any text to be printed
EditText myTextbox;
// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);
// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// This will find a bluetooth printer device
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// MP300 is the name of the bluetooth printer device
if (device.getName().equals("MP300")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tries to open a connection to the bluetooth printer device
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// After opening a connection to bluetooth printer device,
// we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Close the connection to bluetooth printer.
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />
<EditText
android:id="#+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/label"
android:background="#android:drawable/editbox_background" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/entry"
android:layout_marginLeft="10dip"
android:text="Open" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/open"
android:layout_toLeftOf="#id/open"
android:text="Send" />
<Button
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/send"
android:layout_toLeftOf="#id/send"
android:text="Close" />
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothprinter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Result pictures are below:
I am trying to connect arduino Uno to android device using Wifi over a Common Lan connection but the following code is not giving me any response from Arduino. Arduino is working well with the desktop checking code.Here is my android part of the code on click of a toggle button
//WIFI socket code
ToggleButton toggle = (ToggleButton) findViewById(R.id.wifiTButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// wifi thread code
final Runnable r = new Runnable()
{
public void run()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
textOut = (TextView) findViewById(R.id.textOut);
textIn=(EditText) findViewById(R.id.textIn);
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111111);
//dataOutputStream.writeUTF("111111".toString() );//textOut.getText().toString());
textIn.setText(dataInputStream.readByte());
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
}
});
I was able to solve the problem. It is running well with the command button instead of a toggle button and properly using the thread syntax.
Here is a sample application mainActivity code.
package com.example.arduinoandroid;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler handler;
String TAG = "main Activity";
Button bt1;
TextView textOut;
EditText editIn;
static byte abc;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
class Task implements Runnable {
#Override
public void run() {
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111);
// dataOutputStream.writeUTF("111111".toString()
// );//textOut.getText().toString());
abc = dataInputStream.readByte();
Toast.makeText(getBaseContext(), abc, Toast.LENGTH_SHORT)
.show();
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textOut.setText("working ae");
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
// WIFI socket code
bt1 = (Button) findViewById(R.id.chkButton1);
textOut = (TextView) findViewById(R.id.textOut);
editIn = (EditText) findViewById(R.id.editIn);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Task()).start();
}
});
}
}
and the code for xml part is
<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"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/chkButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="140dp"
android:text="Check wifi" />
<TextView
android:id="#+id/textOut"
android:layout_width="wrap_content"
android:layout_height="39dp"
android:layout_gravity="bottom|right"
android:text="Output" />
<EditText
android:id="#+id/editIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:text="111111"/>
</LinearLayout>
Please include the following permissions in the manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
I'm sort of new to Android application development. I already created a very simple application that turns the device's flashlight on/off.
I'd like to try and create a messaging application where you can chat with your friends when both of you are connected to a Wifi. Sort of like "WhatsApp", "Viber", etc..
I would be really happy if you could give me guidelines and help me get the idea of how to develop such an application.
Thank you so much,
Orel.
For that you need to create server program, that will authenticate username & password and communication between diff users.., etc, and you need to send the response based on the user query.
For any network communication application consists of two components:
Server
Client
In the case of WhatsApp android app,its a client application which communicate's with the WhatsApp server.
The server with exchange the data from one client to another client, the client may be desktop, android mobile, iPhone,...etc
Generally chat programs will implemented using sockets, and its depends upon the architecture and technologies which you will chose.
Using this:
ChatServerSide
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ChatServerSide extends Activity implements View.OnClickListener {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
TextView tvMyIp;
Socket socket;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tvMyIp.setText("Waiting devices on " + getIpAddress());
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
String read = null;
try {
read = input.readLine();
if (read == null) {
read = "Client has leave the chat";
socket.close();
updateConversationHandler.post(new updateUIThread(read));
break;
}
updateConversationHandler.post(new updateUIThread("Client Says: " + read));
}catch(IOException e){
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + msg + "\n");
}
}
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 += inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
ChatClientSide
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientSide extends Activity implements View.OnClickListener {
private Handler handler = new Handler();
private Socket socket;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
Handler updateConversationHandler;
TextView tvMyIp;
private static final int SERVERPORT = 6000;
private static String SERVER_IP = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
SERVER_IP = ActivityMain.ipToConnect;
updateConversationHandler = new Handler();
receiveMsg();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getServerIp(Intent intent) {
Bundle bundle = intent.getExtras();
String ip = bundle.getString("destAdress");
tvMyIp.setText("Is connected to " + ip);
return ip;
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
final String host = SERVER_IP;
BufferedReader in = null;
try {
socket = new Socket(host, SERVERPORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
//msgList.add(msg);
} catch (IOException e) {
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "Server Says: " + mssg + "\n");
}
});
}
}
chat_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvMyIp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnSendMsg"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="send"
android:layout_weight="0" />
<EditText
android:id="#+id/etInputMesage"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tvOutputMessage"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
</LinearLayout>
</LinearLayout>
I'm developing an Android application (client) and want it to connect with my Java server using TCP communication.
I've done the code - simple program, client send a message and server echos it back - as below:
Server code:
import java.net.*;
public class Server {
public static void main(String[] args) {
int nreq = 1;
try
{
ServerSocket sock = new ServerSocket (8080);
for (;;)
{
Socket newsock = sock.accept();
System.out.println("Creating thread ...");
Thread t = new ThreadHandler(newsock,nreq);
t.start();
}
}
catch (Exception e)
{
System.out.println("IO error " + e);
}
System.out.println("End!");
}
}
a Thread Handler code in the same project file of the server:
import java.io.*;
import java.net.*;
class ThreadHandler extends Thread {
Socket newsock;
int n;
ThreadHandler(Socket s, int v) {
newsock = s;
n = v;
}
public void run() {
try {
PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
BufferedReader inp = new BufferedReader(new InputStreamReader(
newsock.getInputStream()));
outp.println("Hello :: enter QUIT to exit \n");
boolean more_data = true;
String line;
while (more_data) {
line = inp.readLine();
System.out.println("Message '" + line + "' echoed back to client.");
if (line == null) {
System.out.println("line = null");
more_data = false;
} else {
outp.println("From server: " + line + ". \n");
if (line.trim().equals("QUIT"))
more_data = false;
}
}
newsock.close();
System.out.println("Disconnected from client number: " + n);
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
}
And this is the Client side (Android):
package com.android.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Client extends Activity {
/** Called when the activity is first created. */
Scanner scanner = new Scanner(System.in);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText msg = (EditText) findViewById(R.id.etMsg);
Button send = (Button) findViewById(R.id.bSend);
final TextView convo = (TextView) findViewById(R.id.tvConvo);
final TextView status = (TextView) findViewById(R.id.tvStatus);
try {
send.setOnClickListener(new View.OnClickListener() {
Socket s = new Socket("localhost", 8080);
String message = msg.getText().toString();
#Override
public void onClick(View v) {
status.setText("...");
PrintWriter outp = null;
BufferedReader inp = null;
status.setText("Established connection..");
String serverMsg = null;
try {
outp = new PrintWriter(s.getOutputStream(), true);
inp = new BufferedReader(new InputStreamReader(s.getInputStream()));
serverMsg = inp.readLine();
} catch (IOException e) {
e.printStackTrace();
}
convo.append(serverMsg + "\n");
if (message != null) {
if (msg.getText().toString().trim() == "QUIT") {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
status.setText("Disconnected from server.");
} else {
try {
convo.append(message + "\n");
outp.println(message);
serverMsg = inp.readLine();
convo.append(serverMsg + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
else
status.setText("Problem in connection..!");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the XML file:
<?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:id="#+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Your message here:" />
- <EditText android:id="#+id/etMsg" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10">
<requestFocus />
</EditText>
<TextView android:id="#+id/tvStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Status..." android:textAppearance="?android:attr/textAppearanceSmall" />
<Button android:id="#+id/bSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" />
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Conversation:" android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView android:id="#+id/tvConvo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" />
</LinearLayout>
I tried running it, but nothing happens. When I click the button the TextView doesn't view the "Hello" message from the server.
You connect with your Android client to localhost.
Socket s = new Socket("localhost", 8080);
This would only work when your server is running on the Android device. But I think it is running on your PC. So, when you run your app on Android emulator, you can connect to 10.0.2.2 in order to contact the host. On a real device, you have to find out your servers IP address which can be reached by the Android device, e.g. via Wi-Fi.
If your server is on Windows, type cmd in the Start menu search box and then type ipconfig at the command prompt. You will see something like IVP4 Address----- 192.168.0.101. you need to use this address and port number on your client.
I am writing a code that needs to send data from Android mobile to desktop computer (linux server) every second. Since the data is send very often, this cannot be achieved via Http hit (as it consumes times), Tcp communication seems a better option as the data from android phone can be send very quickly through this socket programming.
The code of client on Android phone is:
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GetWebPage extends Activity {
//Handler h;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText eText = (EditText) findViewById(R.id.address);
final TextView tView = (TextView) findViewById(R.id.pagetext);
final Button button = (Button) findViewById(R.id.ButtonGo);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
Log.v("Tcp","Clicked the button");
InetAddress serveraddress=InetAddress.getByName("67.23.14.156");
Log.v("Tcp", "Got the InetAddress");
Socket s = new Socket(serveraddress,4447);
Log.v("Tcp","Got the Socket address");
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
out.close();
} catch (UnknownHostException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
} catch (IOException e) {
tView.setText(e.toString());
Log.v("Tcp",e.toString());
}catch (Exception e) {
tView.setText(e.toString());
}
}
});
}
}
The server side code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ListenIncomingTcpConnection {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket client=null;
try {
System.out.println("Creating the server object...");
serverSocket = new ServerSocket(4447);
System.out.println("Waiting for the connection...");
} catch (IOException e1) {
System.out.println(e1);
}
while (true) {
try {
client = serverSocket.accept();
System.out.println("Reading the content...");
} catch (IOException e1) {
System.out.println(e1);
e1.printStackTrace();
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("Reading the content.....");
} catch(Exception e) {
System.out.println(e);
} finally {
try{
client.close();
}catch(Exception e){
System.out.println(e);
}
}
}//while
}//PSVM
}
The code of manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spce" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="GetWebPage">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
</manifest>
I have executed the server code on the linux machine via "java" command on putty. It executed and stopped at this line "client = serverSocket.accept();"
When I execute the client on android mobile, it says:
Clicked the button
Got the InetAddress
java.net.SocketException: No route to host
I am not able to spot the reason of this No route to host.
Please help in solving the problem.
Looks like you're doing a DNS lookup on an IP address
serveraddress=InetAddress.getByName("67.23.14.156")
Try to use the IP address directly.
new Socket("67.23.14.156",4447);