Search in sources :

Example 51 with ChannelInboundHandlerAdapter

use of io.netty.channel.ChannelInboundHandlerAdapter in project baseio by generallycloud.

the class TestLoadEchoClient1 method prepare.

@Override
public void prepare() throws Exception {
    eventHandleAdaptor = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            // System.out.println("_________________"+msg);
            // ctx.write(msg);
            addCount(1);
        }
    };
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, false);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
            pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast("handler", eventHandleAdaptor);
        }
    });
    f = b.connect("localhost", 5656).sync();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 52 with ChannelInboundHandlerAdapter

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

the class WebSocketServerProtocolHandler method forbiddenHttpRequestResponder.

static ChannelHandler forbiddenHttpRequestResponder() {
    return new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof FullHttpRequest) {
                ((FullHttpRequest) msg).release();
                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN);
                ctx.channel().writeAndFlush(response);
            } else {
                ctx.fireChannelRead(msg);
            }
        }
    };
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 53 with ChannelInboundHandlerAdapter

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

the class ByteToMessageDecoderTest method testFireChannelReadCompleteOnInactive.

@Test
public void testFireChannelReadCompleteOnInactive() throws InterruptedException {
    final BlockingQueue<Integer> queue = new LinkedBlockingDeque<Integer>();
    final ByteBuf buf = Unpooled.buffer().writeBytes(new byte[] { 'a', 'b' });
    EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int readable = in.readableBytes();
            assertTrue(readable > 0);
            in.skipBytes(readable);
        }

        @Override
        protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            assertFalse(in.isReadable());
            out.add("data");
        }
    }, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            queue.add(3);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            queue.add(1);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            if (!ctx.channel().isActive()) {
                queue.add(2);
            }
        }
    });
    assertFalse(channel.writeInbound(buf));
    channel.finish();
    assertEquals(1, (int) queue.take());
    assertEquals(2, (int) queue.take());
    assertEquals(3, (int) queue.take());
    assertTrue(queue.isEmpty());
}
Also used : LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 54 with ChannelInboundHandlerAdapter

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

the class FlowControlHandlerTest method testAutoReadingOn.

/**
     * This test demonstrates the default behavior if auto reading
     * is turned on from the get-go and you're trying to turn it off
     * once you've received your first message.
     *
     * NOTE: This test waits for the client to disconnect which is
     * interpreted as the signal that all {@code byte}s have been
     * transferred to the server.
     */
@Test
public void testAutoReadingOn() throws Exception {
    final CountDownLatch latch = new CountDownLatch(3);
    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ReferenceCountUtil.release(msg);
            // We're turning off auto reading in the hope that no
            // new messages are being sent but that is not true.
            ctx.channel().config().setAutoRead(false);
            latch.countDown();
        }
    };
    Channel server = newServer(true, handler);
    Channel client = newClient(server.localAddress());
    try {
        client.writeAndFlush(newOneMessage()).syncUninterruptibly();
        // We received three messages even through auto reading
        // was turned off after we received the first message.
        assertTrue(latch.await(1L, SECONDS));
    } finally {
        client.close();
        server.close();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 55 with ChannelInboundHandlerAdapter

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

the class FlowControlHandlerTest method testFlowToggleAutoRead.

/**
     * The {@link FlowControlHandler} will pass down messages one by one
     * if {@link ChannelConfig#setAutoRead(boolean)} is being toggled.
     */
@Test
public void testFlowToggleAutoRead() throws Exception {
    final Exchanger<Channel> peerRef = new Exchanger<Channel>();
    final CountDownLatch msgRcvLatch1 = new CountDownLatch(1);
    final CountDownLatch msgRcvLatch2 = new CountDownLatch(1);
    final CountDownLatch msgRcvLatch3 = new CountDownLatch(1);
    final CountDownLatch setAutoReadLatch1 = new CountDownLatch(1);
    final CountDownLatch setAutoReadLatch2 = new CountDownLatch(1);
    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {

        private int msgRcvCount;

        private int expectedMsgCount;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            peerRef.exchange(ctx.channel(), 1L, SECONDS);
            ctx.fireChannelActive();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException {
            ReferenceCountUtil.release(msg);
            // Disable auto reading after each message
            ctx.channel().config().setAutoRead(false);
            if (msgRcvCount++ != expectedMsgCount) {
                return;
            }
            switch(msgRcvCount) {
                case 1:
                    msgRcvLatch1.countDown();
                    if (setAutoReadLatch1.await(1L, SECONDS)) {
                        ++expectedMsgCount;
                    }
                    break;
                case 2:
                    msgRcvLatch2.countDown();
                    if (setAutoReadLatch2.await(1L, SECONDS)) {
                        ++expectedMsgCount;
                    }
                    break;
                default:
                    msgRcvLatch3.countDown();
                    break;
            }
        }
    };
    FlowControlHandler flow = new FlowControlHandler();
    Channel server = newServer(true, flow, handler);
    Channel client = newClient(server.localAddress());
    try {
        // The client connection on the server side
        Channel peer = peerRef.exchange(null, 1L, SECONDS);
        client.writeAndFlush(newOneMessage()).syncUninterruptibly();
        // channelRead(1)
        assertTrue(msgRcvLatch1.await(1L, SECONDS));
        // channelRead(2)
        peer.config().setAutoRead(true);
        setAutoReadLatch1.countDown();
        assertTrue(msgRcvLatch1.await(1L, SECONDS));
        // channelRead(3)
        peer.config().setAutoRead(true);
        setAutoReadLatch2.countDown();
        assertTrue(msgRcvLatch3.await(1L, SECONDS));
        assertTrue(flow.isQueueEmpty());
    } finally {
        client.close();
        server.close();
    }
}
Also used : Exchanger(java.util.concurrent.Exchanger) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)103 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)75 Channel (io.netty.channel.Channel)65 Test (org.junit.Test)62 Bootstrap (io.netty.bootstrap.Bootstrap)51 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)48 ChannelFuture (io.netty.channel.ChannelFuture)33 CountDownLatch (java.util.concurrent.CountDownLatch)32 EventLoopGroup (io.netty.channel.EventLoopGroup)28 InetSocketAddress (java.net.InetSocketAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)23 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)23 ByteBuf (io.netty.buffer.ByteBuf)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)17 LocalServerChannel (io.netty.channel.local.LocalServerChannel)17 SocketChannel (io.netty.channel.socket.SocketChannel)17 LocalAddress (io.netty.channel.local.LocalAddress)16 LocalChannel (io.netty.channel.local.LocalChannel)16 AtomicReference (java.util.concurrent.atomic.AtomicReference)15