Set websocket read timeout to keepalive interaval + 10s.

// FREEBIE
This commit is contained in:
Moxie Marlinspike 2015-04-05 15:18:08 -07:00
parent e02aea9cfb
commit 25a38b9eea
2 changed files with 15 additions and 10 deletions

View File

@ -48,13 +48,13 @@ public class OkHttpClientWrapper implements WebSocketListener {
this.listener = listener;
}
public void connect() {
public void connect(final int timeout, final TimeUnit timeUnit) {
new Thread() {
@Override
public void run() {
int attempt = 0;
while ((webSocket = newSocket()) != null) {
while ((webSocket = newSocket(timeout, timeUnit)) != null) {
try {
Response response = webSocket.connect(OkHttpClientWrapper.this);
@ -117,14 +117,17 @@ public class OkHttpClientWrapper implements WebSocketListener {
listener.onClose();
}
private synchronized WebSocket newSocket() {
private synchronized WebSocket newSocket(int timeout, TimeUnit unit) {
if (closed) return null;
String filledUri = String.format(uri, credentialsProvider.getUser(), credentialsProvider.getPassword());
SSLSocketFactory socketFactory = createTlsSocketFactory(trustStore);
OkHttpClient okHttpClient = new OkHttpClient();
return WebSocket.newWebSocket(new OkHttpClient().setSslSocketFactory(socketFactory),
new Request.Builder().url(filledUri).build());
okHttpClient.setSslSocketFactory(createTlsSocketFactory(trustStore));
okHttpClient.setReadTimeout(timeout, unit);
okHttpClient.setConnectTimeout(timeout, unit);
return WebSocket.newWebSocket(okHttpClient, new Request.Builder().url(filledUri).build());
}
private SSLSocketFactory createTlsSocketFactory(TrustStore trustStore) {

View File

@ -20,6 +20,7 @@ import static org.whispersystems.textsecure.internal.websocket.WebSocketProtos.W
public class WebSocketConnection implements WebSocketEventListener {
private static final String TAG = WebSocketConnection.class.getSimpleName();
private static final int KEEPALIVE_TIMEOUT_SECONDS = 55;
private final LinkedList<WebSocketRequestMessage> incomingRequests = new LinkedList<>();
@ -42,7 +43,7 @@ public class WebSocketConnection implements WebSocketEventListener {
if (client == null) {
client = new OkHttpClientWrapper(wsUri, trustStore, credentialsProvider, this);
client.connect();
client.connect(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS);
}
}
@ -140,6 +141,7 @@ public class WebSocketConnection implements WebSocketEventListener {
public synchronized void onConnected() {
if (client != null && keepAliveSender == null) {
Log.w(TAG, "onConnected()");
keepAliveSender = new KeepAliveSender();
keepAliveSender.start();
}
@ -156,7 +158,7 @@ public class WebSocketConnection implements WebSocketEventListener {
public void run() {
while (!stop.get()) {
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(55));
Thread.sleep(TimeUnit.SECONDS.toMillis(KEEPALIVE_TIMEOUT_SECONDS));
Log.w(TAG, "Sending keep alive...");
sendKeepAlive();