Search in sources :

Example 96 with ChannelFuture

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

the class WebSocketClientProtocolHandshakeHandler method channelActive.

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    handshaker.handshake(ctx.channel()).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                ctx.fireExceptionCaught(future.cause());
            } else {
                ctx.fireUserEventTriggered(WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_ISSUED);
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 97 with ChannelFuture

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

the class WebSocketServerProtocolHandshakeHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    final FullHttpRequest req = (FullHttpRequest) msg;
    if (isNotWebSocketPath(req)) {
        ctx.fireChannelRead(msg);
        return;
    }
    try {
        if (req.method() != GET) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
            return;
        }
        final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols, allowExtensions, maxFramePayloadSize, allowMaskMismatch);
        final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
            handshakeFuture.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    } else {
                        // Kept for compatibility
                        ctx.fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                        ctx.fireUserEventTriggered(new WebSocketServerProtocolHandler.HandshakeComplete(req.uri(), req.headers(), handshaker.selectedSubprotocol()));
                    }
                }
            });
            WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
            ctx.pipeline().replace(this, "WS403Responder", WebSocketServerProtocolHandler.forbiddenHttpRequestResponder());
        }
    } finally {
        req.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 98 with ChannelFuture

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

the class WebSocketServerExtensionHandler method write.

@Override
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof HttpResponse && WebSocketExtensionUtil.isWebsocketUpgrade(((HttpResponse) msg).headers()) && validExtensions != null) {
        HttpResponse response = (HttpResponse) msg;
        String headerValue = response.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
        for (WebSocketServerExtension extension : validExtensions) {
            WebSocketExtensionData extensionData = extension.newReponseData();
            headerValue = WebSocketExtensionUtil.appendExtension(headerValue, extensionData.name(), extensionData.parameters());
        }
        promise.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    for (WebSocketServerExtension extension : validExtensions) {
                        WebSocketExtensionDecoder decoder = extension.newExtensionDecoder();
                        WebSocketExtensionEncoder encoder = extension.newExtensionEncoder();
                        ctx.pipeline().addAfter(ctx.name(), decoder.getClass().getName(), decoder);
                        ctx.pipeline().addAfter(ctx.name(), encoder.getClass().getName(), encoder);
                    }
                }
                ctx.pipeline().remove(ctx.name());
            }
        });
        if (headerValue != null) {
            response.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, headerValue);
        }
    }
    super.write(ctx, msg, promise);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 99 with ChannelFuture

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

the class SocketConnectionAttemptTest method testConnectTimeout.

public void testConnectTimeout(Bootstrap cb) throws Throwable {
    cb.handler(new TestHandler()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
    ChannelFuture future = cb.connect(BAD_HOST, BAD_PORT);
    try {
        assertThat(future.await(3000), is(true));
    } finally {
        future.channel().close();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture)

Example 100 with ChannelFuture

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

the class SocketGatheringWriteTest method testGatheringWrite0.

private void testGatheringWrite0(ServerBootstrap sb, Bootstrap cb, byte[] data, boolean composite, boolean autoRead) throws Throwable {
    sb.childOption(ChannelOption.AUTO_READ, autoRead);
    cb.option(ChannelOption.AUTO_READ, autoRead);
    final TestHandler sh = new TestHandler(autoRead);
    final TestHandler ch = new TestHandler(autoRead);
    cb.handler(ch);
    sb.childHandler(sh);
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect().sync().channel();
    for (int i = 0; i < data.length; ) {
        int length = Math.min(random.nextInt(1024 * 8), data.length - i);
        ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
        if (composite && i % 2 == 0) {
            int split = buf.readableBytes() / 2;
            int size = buf.readableBytes() - split;
            int oldIndex = buf.writerIndex();
            buf.writerIndex(split);
            ByteBuf buf2 = Unpooled.buffer(size).writeBytes(buf, split, oldIndex - split);
            CompositeByteBuf comp = Unpooled.compositeBuffer();
            comp.addComponent(true, buf).addComponent(true, buf2);
            cc.write(comp);
        } else {
            cc.write(buf);
        }
        i += length;
    }
    ChannelFuture cf = cc.writeAndFlush(Unpooled.EMPTY_BUFFER);
    assertNotEquals(cc.voidPromise(), cf);
    try {
        assertTrue(cf.await(30000));
        cf.sync();
    } catch (Throwable t) {
        // TODO: Remove this once we fix this test.
        TestUtils.dump(StringUtil.simpleClassName(this));
        throw t;
    }
    while (sh.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
    assertEquals(0, ch.counter);
    assertEquals(Unpooled.wrappedBuffer(data), sh.received);
}
Also used : CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) IOException(java.io.IOException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ChannelFuture (io.netty.channel.ChannelFuture)361 Test (org.junit.Test)128 Channel (io.netty.channel.Channel)114 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)102 Bootstrap (io.netty.bootstrap.Bootstrap)93 ChannelFutureListener (io.netty.channel.ChannelFutureListener)86 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)86 ByteBuf (io.netty.buffer.ByteBuf)81 InetSocketAddress (java.net.InetSocketAddress)78 EventLoopGroup (io.netty.channel.EventLoopGroup)71 IOException (java.io.IOException)69 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelPipeline (io.netty.channel.ChannelPipeline)63 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)59 ClosedChannelException (java.nio.channels.ClosedChannelException)56 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 ArrayList (java.util.ArrayList)46 ChannelInitializer (io.netty.channel.ChannelInitializer)45 Http2Headers (io.netty.handler.codec.http2.Http2Headers)44 SslHandler (io.netty.handler.ssl.SslHandler)44