Re: Java (android) socket reconnection
My whole code looks like. I have to use to threads due to manage obtaining data from server too. Could You look at it in free time and tell me what's wrong?
Regards
Artik
public class MainActivity extends Activity {
Button button;
TextView textview1;
public Socket sock = null;
private BufferedWriter out;
private Thread thrd2, thrd1;
private static String address = "xyz";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
textview1 = (TextView) findViewById(R.id.editText1);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
if (out != null) {
out.write("TEST DATA\n");
out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// if sock is null wait 300ms
else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
try {
stopSocket();
Thread.sleep(1000);
} catch (InterruptedException e1) {
e.printStackTrace();
}
}
}
}
});
thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
if (sock == null)
try {
sock = new Socket();
sock.connect(new InetSocketAddress(address,
5000), 1000);
sock.setSoLinger(true, 1);
sock.setTcpNoDelay(true);
out = new BufferedWriter(
new OutputStreamWriter(sock
.getOutputStream()));
if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();
} catch (UnknownHostException e) {
stopSocket();
} catch (IOException e) {
stopSocket();
}
}
;
}
});
if ((thrd1 != null) && (!thrd1.isAlive()))
thrd1.start();
};
});
}
public void stopSocket() {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
Log.d("-----", e.getMessage() + " " + e.getCause());
}
try {
if (sock != null) {
sock.close();
}
sock = null;
} catch (IOException e) {
Log.d("-----", e.getMessage() + " " + e.getCause());
sock = null;
out = null;
}
}
}