I am trying to connect from my android phone to my server. But I got time-out connection error.
what can be the the cause?
my code is
public void onClick(View view) {
if (view == loginBtn) {
if (username.getText().length() != 0 & password.getText().length() != 0) {
progressDialog = ProgressDialog.show(this,Farsi.Convert(""),"Verifying user credential");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Connection connection = getConnection();
User user = connection.login(username.getText().toString(), password.getText().toString());
if (user != null) {
BaseKaizenActivity.getStorageManager().setUser(user);
Log.d("---", user.getId() + " : " + user.getName());
showActivity(MainMenuActivity.class);
}
else {
handleException("Invalid username or password");
}
}
catch (Exception exc) {
handleException(exc.getMessage());
}
finally {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
});
thread.start();
}
else {
handleException("Insert username and password");
}
}
}
The exception I got is
Connect to /10.0.2.2:8080 timed out
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8080 timed out
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(
DefaultClientConnectionOperator.java:156)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.pda.kaizen.ConnectionImpl.executeHttpPost(ConnectionImpl.java:133)
at com.pda.kaizen.ConnectionImpl.login(ConnectionImpl.java:88)
at com.pda.kaizen.activity.LoginActivity$1.run(LoginActivity.java:98)
at java.lang.Thread.run(Thread.java:1019)
Try this sample code:
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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();
}
}
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
and your xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<EditText
android:id="#+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send"
/>
<TextView
android:id="#+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
firts add this per mission in your manifest
<uses-permission android:name="android.permission.INTERNET"/>
Related
I use a bluetooth_access Async task to establish a connection and I need continue to use the input stream and out stream of the bluetooth socket I established.
The issue I having is when I clicked button1 or button2, it sometimes (not all the times) cause Software caused connection abort. It got tripped on out.write(bytes) when clicked.
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
button3 = (Button)this.findViewById(R.id.button3);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
try {
for (int i = 0; i < 3; i++) {
test();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean connected = false;
private BluetoothSocket sock;
private InputStream in;
private OutputStream out;
private Button button1;
private Button button2;
private Button button3;
private TextView data_t;
private BufferedReader in_read;
public void test() throws Exception {
if (connected) {
return;
}
new bluetooth_access().execute("");
}
#Override
public void onClick(View v){
// TODO Auto-generated method stub
if(v.equals(button1)){
String s = "turn left";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(v.equals(button2)){
String s = "turn right";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new post_data().execute("");
}
if(v.equals(button3)){
String s = "read ADC";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class bluetooth_access extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
BluetoothDevice Pi = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("00:15:83:0C:BF:EB");
Method m=null;
try {
m = Pi.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sock = (BluetoothSocket)m.invoke(Pi, Integer.valueOf(1));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sock.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("PiTest", "++++ Connected");
return null;
}
#Override
protected void onPostExecute(String result) {
;
TextView text = (TextView) findViewById(R.id.textView5);
text.setText("Connected through Bluetooth");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
// original
try {
in = sock.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out=sock.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
You are trying to write to a socket stream from your main UI thread (from onClick), i would consider doing all socket communication from asynctask itself, or another thread if needed.
your connected variable is not being set, not sure if that was intentional, it can cause multiple execution of your bluetooth asynctask.
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 am developing an application to send a request to port 502 and want to read the response from the same port.
This is what i tried so far
public class Autoamtion extends Activity {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.v("on create", "on create");
final ToggleButton fanOn = (ToggleButton) findViewById(R.id.toggleButton1);
fanOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (fanOn.isChecked()) {
Toast.makeText(Autoamtion.this, "Fan is On",
Toast.LENGTH_SHORT).show();
Log.v("on create", "on create");
try {
echoSocket = new Socket("192.168.1.19", 502);
out = new PrintWriter(echoSocket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to:192.168.1.19");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stdIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
echoSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
Toast.makeText(Autoamtion.this, "Fan is Off",
Toast.LENGTH_SHORT).show();
}
});
}
}
i just installed one simulator which opens the port 502. i confirmed that port which gets open after running this simulator.
i just established the connection with 502 port. i am not getting any response from there.
Please guide me through this so i can make this working. Any advice and help would be appreciated .
Thanks
You should post stackTrace as well, to check what's failling.
At least one thing is not consistent in your information, your refer in the text port 503 and in your code you are using echoSocket = new Socket("192.168.1.19", 502); connecting to port 502.
My server code
public class RemoteServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF().toUpperCase());
dataOutputStream.writeUTF("sajol");
} 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();
}
}
if (dataInputStream != null) {
try {
dataInputStream.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();
}
}
}
}
}
}
My client code for android device
public class Client extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Button b = findViewById(R.id.b)
textOut = (EditText) findViewById(R.id.t);
Button buttonSend = (Button) findViewById(R.id.b);
textIn = (TextView) findViewById(R.id.te);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread t = new Thread(r);
t.start();
}
};
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.239", 8888);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("Sajol", e+"");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Sajol", e+"");
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
}
}
};
}
when i run this client code on emulator server response .But when i run client code on real device server program does not response.I found the ip address using in my code by execute ipconfig command on cmd. My pc(windows 7) and android device both are connected to wifi.
i got following exception
java.net.SocketTimeoutException: Connection timed out
Please give me solution
I have an android client that listens to the smartphone's sensors and when it detects a variation in a sensor's value it produces a string (a "command"), and creates a socket and an output stream to send the string to a java server; every sensor listener creates a socket with a different port than the other listeners. I have also a "send" button and a textbox to send any other string to the server. The problem is that while the button "send" works fine and sends all the strings written in the textbox every time i press it, every listener sends the "command" only the first time they detect a variation in the sensors' values..
//listener buttonSend
Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
buttonSend.setEnabled(false);
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try
{
socket = new Socket(IP, 32450);
socket.setReuseAddress(true);
socket.setSoTimeout(2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
}
catch (UnknownHostException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
catch (IOException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
finally
{
if (socket != null)
{
try
{
buttonSend.setEnabled(true);
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
}
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (dataInputStream != null)
{
try
{
dataInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}; //End listener buttonSend
this was the button and all the sensors work like this:
//proximity sensor event listener
SensorEventListener proximitySensorEventListener
= new SensorEventListener()
{
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0)
{
// TODO Auto-generated method stub
if(arg0.sensor.getType()==Sensor.TYPE_PROXIMITY && IP!="")
{
textProximitySensorData.setText("Proximity Sensor Value:"
+ String.valueOf(arg0.values[0]));
String proxValue = "Proximity Sensor: VALUE "
+ String.valueOf(arg0.values[0]);
if(buttonSend.isEnabled()==true){
Socket socket = null;
DataOutputStream dataOutputStream = null;
try
{
socket = new Socket(IP, 32452);
socket.setReuseAddress(true);
socket.setSoTimeout(2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(proxValue);
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
socket=null;
}
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();
}
}
}
}
}
}
};
i tried setSoTimeout but it's useless because it's only for read, and setReuseAddress but it didn't work, logcat and console don't show any error when i run the application, can you help me finding the problem?