Commit f2c2f803 authored by akwizgran's avatar akwizgran

Reconnect if disconnected.

parent 653ca7e6
......@@ -16,7 +16,9 @@ interface Constants {
int ALARM_INTERVAL_MS = 5 * 1000;
int SOCKET_TIMEOUT_MS = 5 * 60 * 1000;
int SOCKET_TIMEOUT_MS = 2 * 60 * 1000;
int CONNECT_TIMEOUT_MS = 30 * 1000;
int RECONNECT_DELAY_MS = 10 * 1000;
}
......@@ -11,6 +11,7 @@ import java.net.Socket;
import static android.content.Context.POWER_SERVICE;
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
import static org.briarproject.snooze.Constants.CONNECT_TIMEOUT_MS;
import static org.briarproject.snooze.Constants.RECONNECT_DELAY_MS;
import static org.briarproject.snooze.Constants.SOCKET_TIMEOUT_MS;
class NetworkThread extends Thread {
......@@ -35,23 +36,45 @@ class NetworkThread extends Thread {
@Override
public void run() {
byte[] buf = new byte[4096];
try {
while (!isInterrupted()) {
Socket s = new Socket();
s.setSoTimeout(SOCKET_TIMEOUT_MS);
log.log("Connecting to " + host + ":" + port);
s.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
InputStream in = s.getInputStream();
log.log("Connected");
for (int read = 0; read != -1 && !isInterrupted(); read = in.read(buf)) {
wakeLock.acquire();
log.log("Read " + read + " bytes");
wakeLock.release();
try {
s.setSoTimeout(SOCKET_TIMEOUT_MS);
log.log("Connecting to " + host + ":" + port);
s.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
InputStream in = s.getInputStream();
log.log("Connected");
for (int read = 0; read != -1 && !isInterrupted(); read = in.read(buf)) {
wakeLock.acquire();
log.log("Read " + read + " bytes");
wakeLock.release();
}
if (isInterrupted()) {
log.log("Network thread interrupted");
tryToClose(s);
return;
} else {
log.log("End of stream");
tryToClose(s);
}
} catch (IOException e) {
log.log("Network error: " + e.toString());
tryToClose(s);
}
try {
sleep(RECONNECT_DELAY_MS);
} catch (InterruptedException e) {
log.log("Network thread interrupted");
return;
}
if (isInterrupted()) log.log("Network thread interrupted");
else log.log("End of stream");
}
}
private void tryToClose(Socket s) {
try {
s.close();
} catch (IOException e) {
log.log(e.toString());
log.log("Error closing socket: " + e);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment