use of com.ning.http.client.websocket.WebSocketListener in project OpenTripPlanner by opentripplanner.
the class WebsocketGtfsRealtimeUpdater method run.
@Override
public void run() throws InterruptedException {
while (true) {
AsyncHttpClient client = new AsyncHttpClient();
WebSocketListener listener = new Listener();
WebSocketUpgradeHandler handler = new WebSocketUpgradeHandler.Builder().addWebSocketListener(listener).build();
WebSocket socket = null;
boolean connectionSuccessful = true;
// Try to create a websocket connection
try {
socket = client.prepareGet(url).execute(handler).get();
LOG.info("Successfully connected to {}.", url);
} catch (ExecutionException e) {
LOG.error("Could not connect to {}: {}", url, e.getCause().getMessage());
connectionSuccessful = false;
} catch (Exception e) {
LOG.error("Unknown exception when trying to connect to {}:", url, e);
connectionSuccessful = false;
}
// If connection was unsuccessful, wait some time before trying again
if (!connectionSuccessful) {
Thread.sleep(reconnectPeriodSec * 1000);
}
// Keep checking whether connection is still open
while (true) {
if (socket == null || !socket.isOpen()) {
// The connection is closed somehow, try to reconnect
if (connectionSuccessful) {
LOG.warn("Connection to {} was lost. Trying to reconnect...", url);
}
break;
}
Thread.sleep(CHECK_CONNECTION_PERIOD_SEC * 1000);
}
client.close();
}
}
Aggregations