Android Software caused connection abort and Async task - android

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.

Related

Connect/disconnect operations inside another thread

I defined connection variable in top of the main class:
private XMPPConnection connection;
I am connecting to server with following code:
public void connect(final String username,final String password) {
Thread t=new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig=new ConnectionConfiguration("server ip", 5222,"localhost");
XMPPConnection connection=new XMPPTCPConnection(connConfig);
try{
connection.connect();
}catch(XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username,password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setConnection(connection);
}
});
t.start();
}
You see I am using thread for this operation.And if connection was successful setConnection method is calling.
setConnection method:
public void setConnection(XMPPConnection connection) {
this.connection=connection;
if (connection != null) {
//Other stuff
....
So,I am setting connection variable inside thread.But when I want to disconnect from server i am getting crash report.
Disconnect code:
try{
connection.disconnect();
}catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Report:
01-27 14:14:05.162: E/XMPPConnection(3160): Error in listener while closing connection
01-27 14:14:05.162: E/XMPPConnection(3160): android.os.NetworkOnMainThreadException
01-27 14:14:05.162: E/XMPPConnection(3160): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.getLocalHost(InetAddress.java:365)
01-27 14:14:05.162: E/XMPPConnection(3160): at org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy.<init>(Socks5Proxy.java:108)
I know this error.Android doesn't allow to use network operations from ui thread.But I already set connection inside another thread.Why do i need one more thread for disconnect operation ?
I followed this tutorial:http://developer.samsung.com/technical-doc/view.do?v=T000000119
And in this tutorial they didn't use another thread for disconnect.Why I am getting this error ?
Using you code which you have posted. define strict mode thread policy permission in onCreate method of Activity or Application
Assuming you have given INTERNET permission in manifest
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
If you dont wants to use the code which you have posted thn alternate solutions for that below i hve mentioned
Use Async task for the Network related operation or long process related
public class MyActivity extends Activity {
XMPPConnection connection;
private String username;
private String password;
public void connect(final String username, final String password) {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class XMPPConnection extends AsyncTask<Void, Void, Void> {
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... params) {
connect(username, password);
return null;
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// from here update the ui and make ui related changes once
// onpostExecute is called
setConnection(connection);
}
}
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.test_layout);
username = "username#chat.abc.com";
password = "1234567";
new XMPPConnection().execute();
}
}
also Please check this
For async and ui changes , network related operation on main thread related please check this
and make sure setConnection(XMPPConnection connection) you are not doing any UI update related things..
OR you can also try
XMPPTCPConnection connection;
#Override
protected void onResume() {
super.onResume();
connect(LOGGED_USERNAME,"pass");
}
#Override
public void onPause() {
super.onPause();
try{
connection.disconnect();
}catch (SmackException e) {
e.printStackTrace();
}
}
private Handler handler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
setConnection(connection);
}
};
public void connect(final String username, final String password) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessageAtTime(0, 1000);
}
});
t.start();
}
public void setConnection(XMPPTCPConnection connection) {
this.connection=connection;
if (connection != null) {
....

Android App Async Failing to load internal data

I'm currently learning about IO and Async but am having issues. I'm following a guide, and according to the guide this is supposed to work. I have created an activity with a simple EditText, TextView, and 2 Buttons(save and load). I am trying to have the save button take the text in the EditText and save to internal storage, and the load button take whatever is saved and set the TextView as that. Everything works flawlessly when I put all the code to run in the UI thread, but if I change the code to have the UI thread call the Async class for the loading, nothing seems to happen.
**Packages and imports have been removed to save space.
public class InternalData extends Activity implements OnClickListener {
EditText etSharedData;
TextView tvDataResults;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
}
private void setupVariables() {
Button bSave = (Button) findViewById(R.id.bSave);
Button bLoad = (Button) findViewById(R.id.bLoad);
etSharedData = (EditText) findViewById(R.id.etSharedPrefs);
tvDataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
bSave.setOnClickListener(this);
bLoad.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
String sData = etSharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(sData.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fis.close();
tvDataResults.setText(sCollected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
The previous code makes everything work, but the UI lags a bit when trying to load large strings. When I try to have an LoadSomeStuff(Async) class do the loading, it does absolutely nothing when I hit Load on my phone. Within the LoadSomeStuff class it has the doInBackground method open the file and read the data into a string then return that string, and the onPostExecute method set the TextView's text to the returned String. Here's the code:
The onClick method for load button has:
new LoadSomeStuff().execute(FILENAME);
LoadSomeStuff Class *Note: This class is declared within the InternalData class.
public class LoadSomeStuff extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fis.close();
return sCollected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
tvDataResults.setText(result);
}
}
}
Any help is greatly appreciated, thanks!
It actually looks like I had an extra method or two(like onPreExecute) with no code in them and when I deleted them it starting working.

Android Socket communication Exception

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

Problem when I try to move socket creation code to another activity?

I have an android application created by eclipse.
This application works as a client connecting to a server wirelessly across a socket connection.
I have a problem with the code of socket creation.
When I try to move the code from an activity to another in my application, then it doesn't work.
Here is the first activity, where the code works:
public class MyNewAndroidActivity extends Activity {
protected Socket socket;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button_connect = (Button) findViewById(R.id.button1);
final Button button_disconnect = (Button) findViewById(R.id.button2);
final Button b_forward = (Button) findViewById(R.id.b_forward);
final Button b_backward = (Button) findViewById(R.id.b_backward);
final Button b_right = (Button) findViewById(R.id.b_right);
final Button b_left = (Button) findViewById(R.id.b_left);
final Button b_stop = (Button) findViewById(R.id.b_stop);
button_connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Create socket with time out
//192.168.1.76
// my code which I want to transfer it.
int port = 2005;
SocketAddress sockaddr = new InetSocketAddress("192.168.1.15", port);
socket = new Socket();
int timeoutMs = 2000;
socket.connect(sockaddr, timeoutMs);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
when I convert it to method in another activity then it doesn't work:
public class IBMEyes extends Activity implements SensorListener{
protected static Socket socket;
final String tag = "MyProject";
String state ="off";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
Button b_connect = (Button) findViewById(R.id.button1);
b_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SocketConnect();
}
});
// here is my code that I've transferred it.
public void SocketConnect() {
// TODO Auto-generated method stub
try {
int port = 2005;
SocketAddress sockaddr = new InetSocketAddress("192.168.1.15", port);
socket = new Socket();
int timeoutMs = 2000;
socket.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android Client, Pc Server Socket d'ont work over 3g

I try to create a client server socket beetwen my droid(client) and my PC(server), when i am in local(over wifi) it work perfectely, but when il try over 3G i get this exception when the server try to get clientsocket.getOutputStream()
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
What's the probleme, do eny one know the solution of this?
help please :-(
The Server
public class Server {
ServerSocket serverSocket;
public LinkedBlockingQueue<CDRecCourseDisplay> recCours;
public LinkedList<ClientMail> clientMails;
static Server server;
public static Server getInstance(){
if(server == null){
server = new Server();
}
return server;
}
Server() {
// TODO Auto-generated constructor stub
try {
serverSocket = new ServerSocket(54444);
recCours = new LinkedBlockingQueue<CDRecCourseDisplay>(10);
clientMails = new LinkedList<ClientMail>();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.start();
}
private void start(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true){
try {
Socket socket = serverSocket.accept();
new Thread(new Client(socket)).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public Client(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
if(socket == null) return;
try {
InputStream i = socket.getInputStream();
OutputStream o = socket.getOutputStream();
in = new DataInputStream(i);
out = new DataOutputStream(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test Message");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
Log.d("MESSAGE", buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
}
and the client
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public void run() {
// TODO Auto-generated method stub
boolean conected = false;
while(!conected){
try {
Thread.sleep(500);
socket = new Socket("213.233.216.25", 54444);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
conected = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
}
}
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
log.d("MESSAGE", buf);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test message from the phone");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
Most networks (Wifi and 3G) use NAT. NAT allows outbound connections, but prevents inbound (internet to device) connections.
When your server and device are both on the same network, as in your case, then this works as you are not traversing NAT gateway.
Rationale: what you are trying to do (connecting from internet to device) will not work in most networks.

Categories

Resources