Search in sources :

Example 86 with ChannelFuture

use of io.netty.channel.ChannelFuture in project canal by alibaba.

the class SocketChannelPool method open.

public static SocketChannel open(SocketAddress address) throws Exception {
    final SocketChannel socket = new SocketChannel();
    boot.connect(address).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture arg0) throws Exception {
            if (arg0.isSuccess()) {
                socket.setChannel(arg0.channel(), false);
            }
            synchronized (socket) {
                socket.notify();
            }
        }
    });
    synchronized (socket) {
        socket.wait();
    }
    if (null == socket.getChannel()) {
        throw new IOException("can't create socket!");
    }
    chManager.put(socket.getChannel(), socket);
    return socket;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) IOException(java.io.IOException) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IOException(java.io.IOException)

Example 87 with ChannelFuture

use of io.netty.channel.ChannelFuture in project netty by netty.

the class Http2TestUtil method newVoidPromise.

static ChannelPromise newVoidPromise(final Channel channel) {
    return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE) {

        @Override
        public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
            throw new AssertionFailedError();
        }

        @Override
        public ChannelPromise addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
            throw new AssertionFailedError();
        }

        @Override
        public boolean isVoid() {
            return true;
        }

        @Override
        public boolean tryFailure(Throwable cause) {
            channel().pipeline().fireExceptionCaught(cause);
            return true;
        }

        @Override
        public ChannelPromise setFailure(Throwable cause) {
            tryFailure(cause);
            return this;
        }

        @Override
        public ChannelPromise unvoid() {
            ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
            promise.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        channel().pipeline().fireExceptionCaught(future.cause());
                    }
                }
            });
            return promise;
        }
    };
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelPromise(io.netty.channel.ChannelPromise) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) AssertionFailedError(junit.framework.AssertionFailedError) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 88 with ChannelFuture

use of io.netty.channel.ChannelFuture in project netty by netty.

the class HttpToHttp2ConnectionHandlerTest method testChunkedRequestWithBodyAndTrailingHeaders.

@Test
public void testChunkedRequestWithBodyAndTrailingHeaders() throws Exception {
    final String text = "foooooo";
    final String text2 = "goooo";
    final List<String> receivedBuffers = Collections.synchronizedList(new ArrayList<String>());
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock in) throws Throwable {
            receivedBuffers.add(((ByteBuf) in.getArguments()[2]).toString(UTF_8));
            return null;
        }
    }).when(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), eq(false));
    bootstrapEnv(4, 1, 1);
    final HttpRequest request = new DefaultHttpRequest(HTTP_1_1, POST, "http://your_user-name123@www.example.org:5555/example");
    final HttpHeaders httpHeaders = request.headers();
    httpHeaders.set(HttpHeaderNames.HOST, "www.example.org:5555");
    httpHeaders.add(HttpHeaderNames.TRANSFER_ENCODING, "chunked");
    httpHeaders.add(of("foo"), of("goo"));
    httpHeaders.add(of("foo"), of("goo2"));
    httpHeaders.add(of("foo2"), of("goo2"));
    final Http2Headers http2Headers = new DefaultHttp2Headers().method(new AsciiString("POST")).path(new AsciiString("/example")).authority(new AsciiString("www.example.org:5555")).scheme(new AsciiString("http")).add(new AsciiString("foo"), new AsciiString("goo")).add(new AsciiString("foo"), new AsciiString("goo2")).add(new AsciiString("foo2"), new AsciiString("goo2"));
    final DefaultHttpContent httpContent = new DefaultHttpContent(Unpooled.copiedBuffer(text, UTF_8));
    final LastHttpContent lastHttpContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(text2, UTF_8));
    lastHttpContent.trailingHeaders().add(of("trailing"), of("bar"));
    final Http2Headers http2TrailingHeaders = new DefaultHttp2Headers().add(new AsciiString("trailing"), new AsciiString("bar"));
    ChannelPromise writePromise = newPromise();
    ChannelFuture writeFuture = clientChannel.write(request, writePromise);
    ChannelPromise contentPromise = newPromise();
    ChannelFuture contentFuture = clientChannel.write(httpContent, contentPromise);
    ChannelPromise lastContentPromise = newPromise();
    ChannelFuture lastContentFuture = clientChannel.write(lastHttpContent, lastContentPromise);
    clientChannel.flush();
    assertTrue(writePromise.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(writePromise.isSuccess());
    assertTrue(writeFuture.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(writeFuture.isSuccess());
    assertTrue(contentPromise.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(contentPromise.isSuccess());
    assertTrue(contentFuture.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(contentFuture.isSuccess());
    assertTrue(lastContentPromise.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(lastContentPromise.isSuccess());
    assertTrue(lastContentFuture.awaitUninterruptibly(WAIT_TIME_SECONDS, SECONDS));
    assertTrue(lastContentFuture.isSuccess());
    awaitRequests();
    verify(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(http2Headers), eq(0), anyShort(), anyBoolean(), eq(0), eq(false));
    verify(serverListener).onDataRead(any(ChannelHandlerContext.class), eq(3), any(ByteBuf.class), eq(0), eq(false));
    verify(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(http2TrailingHeaders), eq(0), anyShort(), anyBoolean(), eq(0), eq(true));
    assertEquals(1, receivedBuffers.size());
    assertEquals(text + text2, receivedBuffers.get(0));
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ChannelFuture(io.netty.channel.ChannelFuture) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) AsciiString(io.netty.util.AsciiString) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) AsciiString(io.netty.util.AsciiString) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Test(org.junit.Test)

Example 89 with ChannelFuture

use of io.netty.channel.ChannelFuture in project netty by netty.

the class HttpToHttp2ConnectionHandlerTest method bootstrapEnv.

private void bootstrapEnv(int requestCountDown, int serverSettingsAckCount, int trailersCount) throws Exception {
    final CountDownLatch prefaceWrittenLatch = new CountDownLatch(1);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    requestLatch = new CountDownLatch(requestCountDown);
    serverSettingsAckLatch = new CountDownLatch(serverSettingsAckCount);
    trailersLatch = trailersCount == 0 ? null : new CountDownLatch(trailersCount);
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new DefaultEventLoopGroup());
    sb.channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            serverConnectedChannel = ch;
            ChannelPipeline p = ch.pipeline();
            serverFrameCountDown = new FrameCountDown(serverListener, serverSettingsAckLatch, requestLatch, null, trailersLatch);
            p.addLast(new HttpToHttp2ConnectionHandlerBuilder().server(true).frameListener(serverFrameCountDown).build());
            serverChannelLatch.countDown();
        }
    });
    cb.group(new DefaultEventLoopGroup());
    cb.channel(LocalChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            HttpToHttp2ConnectionHandler handler = new HttpToHttp2ConnectionHandlerBuilder().server(false).frameListener(clientListener).gracefulShutdownTimeoutMillis(0).build();
            p.addLast(handler);
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof Http2ConnectionPrefaceWrittenEvent) {
                        prefaceWrittenLatch.countDown();
                        ctx.pipeline().remove(this);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new LocalAddress("HttpToHttp2ConnectionHandlerTest")).sync().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    assertTrue(prefaceWrittenLatch.await(5, SECONDS));
    assertTrue(serverChannelLatch.await(WAIT_TIME_SECONDS, SECONDS));
}
Also used : FrameCountDown(io.netty.handler.codec.http2.Http2TestUtil.FrameCountDown) ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 90 with ChannelFuture

use of io.netty.channel.ChannelFuture in project netty by netty.

the class Http2ConnectionRoundtripTest method listenerExceptionShouldCloseConnection.

@Test
public void listenerExceptionShouldCloseConnection() throws Exception {
    final Http2Headers headers = dummyHeaders();
    doThrow(new RuntimeException("Fake Exception")).when(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(headers), eq(0), eq((short) 16), eq(false), eq(0), eq(false));
    bootstrapEnv(1, 0, 1, 1);
    // Create a latch to track when the close occurs.
    final CountDownLatch closeLatch = new CountDownLatch(1);
    clientChannel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            closeLatch.countDown();
        }
    });
    // Create a single stream by sending a HEADERS frame to the server.
    runInChannel(clientChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Client.encoder().writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise());
            http2Client.flush(ctx());
        }
    });
    // Wait for the server to create the stream.
    assertTrue(serverSettingsAckLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertTrue(requestLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    // Wait for the close to occur.
    assertTrue(closeLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    assertFalse(clientChannel.isOpen());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Test(org.junit.Test)

Aggregations

ChannelFuture (io.netty.channel.ChannelFuture)383 Test (org.junit.Test)131 Channel (io.netty.channel.Channel)120 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)105 Bootstrap (io.netty.bootstrap.Bootstrap)98 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)94 ChannelFutureListener (io.netty.channel.ChannelFutureListener)88 ByteBuf (io.netty.buffer.ByteBuf)81 InetSocketAddress (java.net.InetSocketAddress)79 EventLoopGroup (io.netty.channel.EventLoopGroup)78 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)76 IOException (java.io.IOException)69 ChannelPipeline (io.netty.channel.ChannelPipeline)67 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)64 ClosedChannelException (java.nio.channels.ClosedChannelException)56 ChannelInitializer (io.netty.channel.ChannelInitializer)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 ArrayList (java.util.ArrayList)46 SslHandler (io.netty.handler.ssl.SslHandler)45 Http2Headers (io.netty.handler.codec.http2.Http2Headers)44