Java 类io.netty.channel.ConnectTimeoutException 实例源码

项目:hekate    文件:NetworkClientTest.java   
@Test
public void testConnectTimeoutFailure() throws Exception {
    NetworkClient<String> client = createClient(f -> f.setConnectTimeout(1));

    repeat(3, i -> {
        NetworkClientCallbackMock<String> callback = new NetworkClientCallbackMock<>();

        assertSame(NetworkClient.State.DISCONNECTED, client.state());

        try {
            get(client.connect(new InetSocketAddress("hekate.io", 81), callback));

            fail("Error was expected");
        } catch (ExecutionException e) {
            assertTrue(e.getCause().toString(), ErrorUtils.isCausedBy(ConnectTimeoutException.class, e));
        }

        assertSame(NetworkClient.State.DISCONNECTED, client.state());
        assertNull(client.remoteAddress());
        assertNull(client.localAddress());
        callback.assertConnects(0);
        callback.assertDisconnects(1);
        callback.assertErrors(1);
        callback.getErrors().forEach(e -> assertTrue(e.toString(), e instanceof ConnectTimeoutException));
    });
}
项目:netty4.0.27Learn    文件:OioSocketChannel.java   
@Override
protected void doConnect(SocketAddress remoteAddress,
        SocketAddress localAddress) throws Exception {
    if (localAddress != null) {
        socket.bind(localAddress);
    }

    boolean success = false;
    try {
        socket.connect(remoteAddress, config().getConnectTimeoutMillis());
        activate(socket.getInputStream(), socket.getOutputStream());
        success = true;
    } catch (SocketTimeoutException e) {
        ConnectTimeoutException cause = new ConnectTimeoutException("connection timed out: " + remoteAddress);
        cause.setStackTrace(e.getStackTrace());
        throw cause;
    } finally {
        if (!success) {
            doClose();
        }
    }
}
项目:netty4study    文件:OioSocketChannel.java   
@Override
protected void doConnect(SocketAddress remoteAddress,
        SocketAddress localAddress) throws Exception {
    if (localAddress != null) {
        socket.bind(localAddress);
    }

    boolean success = false;
    try {
        socket.connect(remoteAddress, config().getConnectTimeoutMillis());
        activate(socket.getInputStream(), socket.getOutputStream());
        success = true;
    } catch (SocketTimeoutException e) {
        ConnectTimeoutException cause = new ConnectTimeoutException("connection timed out: " + remoteAddress);
        cause.setStackTrace(e.getStackTrace());
        throw cause;
    } finally {
        if (!success) {
            doClose();
        }
    }
}
项目:Pulse    文件:PCSession.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    String message;

    if (!(cause instanceof ConnectTimeoutException) && (!(cause instanceof ConnectException) || !cause.getMessage()
            .contains("connection timed out"))) {
        if (cause instanceof ReadTimeoutException) {
            message = "Read timed out.";
        } else if (cause instanceof WriteTimeoutException) {
            message = "Write timed out.";
        } else {
            message = "Internal network exception.";
        }
    } else {
        message = "Connection timed out.";
    }

    this.disconnect(message, cause);
}
项目:lettuce-core    文件:SocketOptionsTest.java   
@Test(timeout = 1000)
public void testConnectTimeout() {

    SocketOptions socketOptions = SocketOptions.builder().connectTimeout(100, TimeUnit.MILLISECONDS).build();
    client.setOptions(ClientOptions.builder().socketOptions(socketOptions).build());

    try {
        client.connect(RedisURI.create("2:4:5:5::1", 60000));
        fail("Missing RedisConnectionException");
    } catch (RedisConnectionException e) {

        if (e.getCause() instanceof ConnectTimeoutException) {
            assertThat(e).hasRootCauseInstanceOf(ConnectTimeoutException.class);
            assertThat(e.getCause()).hasMessageContaining("connection timed out");
            return;
        }

        if (e.getCause() instanceof SocketException) {
            // Network is unreachable or No route to host are OK as well.
            return;
        }
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:OioSocketChannel.java   
@Override
protected void doConnect(SocketAddress remoteAddress,
        SocketAddress localAddress) throws Exception {
    if (localAddress != null) {
        socket.bind(localAddress);
    }

    boolean success = false;
    try {
        socket.connect(remoteAddress, config().getConnectTimeoutMillis());
        activate(socket.getInputStream(), socket.getOutputStream());
        success = true;
    } catch (SocketTimeoutException e) {
        ConnectTimeoutException cause = new ConnectTimeoutException("connection timed out: " + remoteAddress);
        cause.setStackTrace(e.getStackTrace());
        throw cause;
    } finally {
        if (!success) {
            doClose();
        }
    }
}
项目:couchbase-jvm-core    文件:AbstractEndpointTest.java   
@Test
public void shouldForceTimeoutOfSocketConnectDoesNotReturn() {
    BootstrapAdapter bootstrap = mock(BootstrapAdapter.class);
    when(bootstrap.connect()).thenReturn(channel.newPromise()); // this promise never completes
    Endpoint endpoint = new DummyEndpoint(bootstrap, environment);

    Observable<LifecycleState> observable = endpoint.connect();

    TestSubscriber<LifecycleState> testSubscriber = new TestSubscriber<LifecycleState>();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();

    List<Throwable> errors = testSubscriber.getOnErrorEvents();
    assertEquals(1, errors.size());
    assertEquals(ConnectTimeoutException.class, errors.get(0).getClass());

    endpoint.disconnect().subscribe();
}
项目:RxNetty    文件:HttpClientTest.java   
@Test
public void testConnectException2() throws Exception {
    HttpClientBuilder<ByteBuf, ByteBuf> clientBuilder = new HttpClientBuilder<ByteBuf, ByteBuf>("www.google.com", 81);
    HttpClient<ByteBuf, ByteBuf> client = clientBuilder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10).build();
    Observable<HttpClientResponse<ByteBuf>> response = client.submit(HttpClientRequest.createGet("/"));
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> ex = new AtomicReference<Throwable>();
    response.subscribe(new Observer<HttpClientResponse<ByteBuf>>() {
        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            ex.set(e);
            latch.countDown();
        }

        @Override
        public void onNext(HttpClientResponse<ByteBuf> args) {
        }
    });
    latch.await(10, TimeUnit.SECONDS);
    assertTrue(ex.get() instanceof ConnectTimeoutException);
}
项目:xrpc    文件:RetryLoop.java   
public static boolean isRetryException(Throwable exception) {
  if (exception instanceof ConnectException
      || exception instanceof ConnectTimeoutException
      || exception instanceof UnknownHostException) {
    return true;
  }
  return false;
}
项目:navi-pbrpc    文件:ShortAliveConnectionPbrpcClientTest.java   
@Test
public void testNegativeConnectCall() throws Exception {
    asyncCall(new ClientBuilder() {
        @Override
        public PbrpcClient getClient() {
            return PbrpcClientFactory.buildShortLiveConnection("9.9.9.9", 9999);
        }
    }, new ConnectTimeoutException(), false);
}
项目:xio    文件:RetryLoop.java   
public static boolean isRetryException(Throwable exception) {
  if (exception instanceof ConnectException
      || exception instanceof ConnectTimeoutException
      || exception instanceof UnknownHostException) {
    return true;
  }
  return false;
}
项目:robust-android    文件:MessengerChannelHandler.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    if (cause instanceof ConnectTimeoutException) {
        Log.d(TAG, "connection timeout exception");
        return; // no finish, fall through to listener
    }

    mSession.finish(cause);
}
项目:PacketLib    文件:TcpSession.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    String message = null;
    if(cause instanceof ConnectTimeoutException || (cause instanceof ConnectException && cause.getMessage().contains("connection timed out"))) {
        message = "Connection timed out.";
    } else if(cause instanceof ReadTimeoutException) {
        message = "Read timed out.";
    } else if(cause instanceof WriteTimeoutException) {
        message = "Write timed out.";
    } else {
        message = cause.toString();
    }

    this.disconnect(message, cause);
}
项目:hekate    文件:NettyClientHandler.java   
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof SslHandshakeCompletionEvent) {
        if (((SslHandshakeCompletionEvent)evt).isSuccess()) {
            if (debug) {
                log.debug("SSL connection established [to={}]", id);
            }

            handshake(ctx);
        }

        super.userEventTriggered(ctx, evt);
    } else if (evt instanceof AutoReadChangeEvent) {
        if (evt == AutoReadChangeEvent.PAUSE) {
            // Completely ignore read timeouts.
            ignoreTimeouts = -1;
        } else {
            // Ignore next timeout.
            ignoreTimeouts = 1;
        }
    } else if (evt instanceof IdleStateEvent) {
        if (state == CONNECTING || state == CONNECTED) {
            IdleStateEvent idle = (IdleStateEvent)evt;

            if (idle.state() == IdleState.WRITER_IDLE) {
                if (hbFlushed) {
                    // Make sure that we don't push multiple heartbeats to the network buffer simultaneously.
                    // Need to perform this check since remote peer can hang and stop reading
                    // while this channel will still be trying to put more and more heartbeats on its send buffer.
                    hbFlushed = false;

                    ctx.writeAndFlush(Heartbeat.INSTANCE).addListener(hbOnFlush);
                }
            } else {
                // Reader idle.
                // Ignore if auto-reading was disabled since in such case we will not read any heartbeats.
                if (ignoreTimeouts != -1 && ctx.channel().config().isAutoRead()) {
                    // Check if timeout should be ignored.
                    if (ignoreTimeouts > 0) {
                        // Decrement the counter of ignored timeouts.
                        ignoreTimeouts--;
                    } else {
                        if (state == CONNECTING) {
                            ctx.fireExceptionCaught(new ConnectTimeoutException("Timeout while connecting to " + id));
                        } else if (state == CONNECTED) {
                            ctx.fireExceptionCaught(new SocketTimeoutException("Timeout while reading data from " + id));
                        }
                    }
                }
            }
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}