Example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

List of usage examples for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

Introduction

In this page you can find the example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter.

Prototype

ChannelInboundHandlerAdapter

Source Link

Usage

From source file:com.github.liyp.netty.HandlerChainApp.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {//  w  w  w.ja v  a2 s .c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("1");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("2");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("3");
                                ctx.fireChannelActive();
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java

License:Apache License

ChannelInboundHandlerAdapter newStartupHandler(StartupMessage startup) {
    return new ChannelInboundHandlerAdapter() {
        @Override/*from ww  w .jav  a  2  s .c  om*/
        public void channelActive(ChannelHandlerContext context) {
            NettyPgProtocolStream.this.ctx = context;

            if (useSsl) {
                write(SSLHandshake.INSTANCE);
                return;
            }
            write(startup);
            context.pipeline().remove(this);
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext context, Object evt) throws Exception {
            if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) {
                write(startup);
                context.pipeline().remove(this);
            }
        }
    };
}

From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java

License:Apache License

ChannelHandler newProtocolHandler() {
    return new ChannelInboundHandlerAdapter() {
        @Override//w ww .j a v a  2 s .  com
        public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {

            if (msg instanceof NotificationResponse) {
                publishNotification((NotificationResponse) msg);
                return;
            }

            if (isCompleteMessage(msg)) {
                Subscriber<? super Message> subscriber = subscribers.remove();
                subscriber.onNext((Message) msg);
                subscriber.onCompleted();
                return;
            }

            subscribers.peek().onNext((Message) msg);
        }

        @Override
        public void channelInactive(ChannelHandlerContext context) throws Exception {
            exceptionCaught(context, new IOException("Channel state changed to inactive"));
        }

        @Override
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
        public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception {
            Collection<Subscriber<? super Message>> unsubscribe = new LinkedList<>();
            if (subscribers.removeAll(unsubscribe)) {
                unsubscribe.forEach(subscriber -> subscriber.onError(cause));
            }
        }
    };
}

From source file:com.github.zk1931.jzab.transport.NettyTransportTest.java

License:Apache License

@Test(timeout = 10000)
public void testTieBreaker() throws Exception {
    final String peerA = getUniqueHostPort();
    final String peerB = getUniqueHostPort();
    final CountDownLatch disconnectedA = new CountDownLatch(1);
    final CountDownLatch disconnectedB = new CountDownLatch(1);

    Transport.Receiver receiverA = new Transport.Receiver() {
        public void onReceived(String source, Message message) {
            Assert.fail("Handshake should have failed");
        }//from w ww.j  av a 2  s .  c o m

        public void onDisconnected(String source) {
            LOG.debug("Got disconnected from {}", source);
            disconnectedA.countDown();
        }
    };
    Transport.Receiver receiverB = new Transport.Receiver() {
        public void onReceived(String source, Message message) {
            Assert.fail("Handshake should have failed");
        }

        public void onDisconnected(String source) {
            LOG.debug("Got disconnected from {}", source);
            disconnectedB.countDown();
        }
    };

    final NettyTransport transportA = new NettyTransport(peerA, receiverA, getDirectory());
    final NettyTransport transportB = new NettyTransport(peerB, receiverB, getDirectory());
    transportB.channel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            // B initiates another handshake before responding to A's handshake.
            transportB.send(peerA, createAck(new Zxid(0, 0)));
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(msg);
        }
    });

    // A initiates a handshake.
    transportA.send(peerB, createAck(new Zxid(0, 0)));
    disconnectedA.await();
    disconnectedB.await();
    transportA.shutdown();
    transportB.shutdown();
}

From source file:com.github.zk1931.jzab.transport.NettyTransportTest.java

License:Apache License

@Test(timeout = 10000)
public void testHandshakeTimeout() throws Exception {
    final String peerA = getUniqueHostPort();
    final String peerB = getUniqueHostPort();
    final CountDownLatch disconnectedA = new CountDownLatch(1);

    Transport.Receiver receiverA = new Transport.Receiver() {
        public void onReceived(String source, Message message) {
        }/*w  w  w . ja  v  a  2  s. co m*/

        public void onDisconnected(String source) {
            LOG.debug("Got disconnected from {}", source);
            disconnectedA.countDown();
        }
    };
    Transport.Receiver receiverB = new Transport.Receiver() {
        public void onReceived(String source, Message message) {
        }

        public void onDisconnected(String source) {
        }
    };

    final NettyTransport transportA = new NettyTransport(peerA, receiverA, getDirectory());
    final NettyTransport transportB = new NettyTransport(peerB, receiverB, getDirectory());

    // Discard the handshake message.
    transportB.channel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            // discard the message.
        }
    });

    transportA.send(peerB, createAck(new Zxid(0, 0)));
    disconnectedA.await();
    transportA.shutdown();
    transportB.shutdown();
}

From source file:com.jroossien.boxx.util.protocol.TinyProtocol.java

License:Open Source License

private void createServerChannelHandler() {
    // Handle connected channels
    endInitProtocol = new ChannelInitializer<Channel>() {

        @Override// w  w  w  .ja  va2s  .c  om
        protected void initChannel(Channel channel) throws Exception {
            try {
                // This can take a while, so we need to stop the main thread from interfering
                synchronized (networkManagers) {
                    // Stop injecting channels
                    if (!closed) {
                        injectChannelInternal(channel);
                    }
                }
            } catch (Exception e) {
                plugin.getLogger().log(Level.SEVERE, "Cannot inject incomming channel " + channel, e);
            }
        }

    };

    // This is executed before Minecraft's channel handler
    beginInitProtocol = new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(endInitProtocol);
        }

    };

    serverChannelHandler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            Channel channel = (Channel) msg;

            // Prepare to initialize ths channel
            channel.pipeline().addFirst(beginInitProtocol);
            ctx.fireChannelRead(msg);
        }

    };
}

From source file:com.kixeye.kixmpp.KixmppCodecTest.java

License:Apache License

@Test
public void testSampleXmppClientSessionPerLine() throws Exception {
    final AtomicReference<KixmppStreamStart> start = new AtomicReference<>();
    final AtomicReference<KixmppStreamEnd> end = new AtomicReference<>();
    final ArrayList<Element> elements = new ArrayList<>();

    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
        @Override//w w  w .j a v a  2 s . c o  m
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof KixmppStreamStart) {
                start.set((KixmppStreamStart) msg);
            } else if (msg instanceof KixmppStreamEnd) {
                end.set((KixmppStreamEnd) msg);
            } else if (msg instanceof Element) {
                elements.add((Element) msg);
            }
        }
    };

    EmbeddedChannel channel = new EmbeddedChannel(new KixmppCodec(), handler);

    // write a packer per line
    try (InputStream inputStream = this.getClass().getResourceAsStream("/sampleXmppClientSession.xml")) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;
        while ((line = reader.readLine()) != null) {
            channel.writeInbound(channel.alloc().buffer().writeBytes(line.getBytes(StandardCharsets.UTF_8)));
        }
    }

    Assert.assertNotNull(start.get());
    Assert.assertNotNull(end.get());

    Assert.assertEquals(5, elements.size());

    Assert.assertEquals("starttls", elements.get(0).getName());
    Assert.assertEquals("auth", elements.get(1).getName());
    Assert.assertEquals("iq", elements.get(2).getName());
    Assert.assertEquals("iq", elements.get(3).getName());
    Assert.assertEquals("iq", elements.get(4).getName());
}

From source file:com.kixeye.kixmpp.KixmppCodecTest.java

License:Apache License

@Test
public void testSampleXmppClientSessionPer100Chars() throws Exception {
    final AtomicReference<KixmppStreamStart> start = new AtomicReference<>();
    final AtomicReference<KixmppStreamEnd> end = new AtomicReference<>();
    final ArrayList<Element> elements = new ArrayList<>();

    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
        @Override//from   w  w w .j av  a2s  .c o  m
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof KixmppStreamStart) {
                start.set((KixmppStreamStart) msg);
            } else if (msg instanceof KixmppStreamEnd) {
                end.set((KixmppStreamEnd) msg);
            } else if (msg instanceof Element) {
                elements.add((Element) msg);
            }
        }
    };

    EmbeddedChannel channel = new EmbeddedChannel(new KixmppCodec(), handler);

    // write a packer per line
    try (InputStream inputStream = this.getClass().getResourceAsStream("/sampleXmppClientSession.xml")) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        int charsRead = 0;
        char[] chars = new char[100];
        while ((charsRead = reader.read(chars)) != -1) {
            StringWriter writer = new StringWriter();

            for (int i = 0; i < charsRead; i++) {
                writer.append(chars[i]);
            }

            channel.writeInbound(
                    channel.alloc().buffer().writeBytes(writer.toString().getBytes(StandardCharsets.UTF_8)));
        }
    }

    Assert.assertNotNull(start.get());
    Assert.assertNotNull(end.get());

    Assert.assertEquals(5, elements.size());

    Assert.assertEquals("starttls", elements.get(0).getName());
    Assert.assertEquals("auth", elements.get(1).getName());
    Assert.assertEquals("iq", elements.get(2).getName());
    Assert.assertEquals("iq", elements.get(3).getName());
    Assert.assertEquals("iq", elements.get(4).getName());
}

From source file:com.kixeye.kixmpp.KixmppCodecTest.java

License:Apache License

@Test
public void testSampleXmppServerSession() throws Exception {
    final AtomicReference<KixmppStreamStart> start = new AtomicReference<>();
    final AtomicReference<KixmppStreamEnd> end = new AtomicReference<>();
    final ArrayList<Element> elements = new ArrayList<>();

    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
        @Override//from ww  w.  j  a  v a 2s  .c o  m
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof KixmppStreamStart) {
                start.set((KixmppStreamStart) msg);
            } else if (msg instanceof KixmppStreamEnd) {
                end.set((KixmppStreamEnd) msg);
            } else if (msg instanceof Element) {
                elements.add((Element) msg);
            }
        }
    };

    EmbeddedChannel channel = new EmbeddedChannel(new KixmppCodec(), handler);

    // write a packet per line
    try (InputStream inputStream = this.getClass().getResourceAsStream("/sampleXmppServerSession.xml")) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;
        while ((line = reader.readLine()) != null) {
            channel.writeInbound(channel.alloc().buffer().writeBytes(line.getBytes(StandardCharsets.UTF_8)));
        }
    }

    Assert.assertNotNull(start.get());
    Assert.assertNotNull(end.get());

    Assert.assertEquals(6, elements.size());

    Assert.assertEquals("features", elements.get(0).getName());
    Assert.assertEquals("proceed", elements.get(1).getName());
    Assert.assertEquals("success", elements.get(2).getName());
    Assert.assertEquals("iq", elements.get(3).getName());
    Assert.assertEquals("iq", elements.get(4).getName());
    Assert.assertEquals("iq", elements.get(5).getName());
}

From source file:com.kixeye.kixmpp.p2p.node.NodeServerTest.java

License:Apache License

@Test(expected = java.net.BindException.class)
public void portAlreadyInUseTest() {
    final MessageRegistry messageRegistry = new MessageRegistry();
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    NodeServer serverA = new NodeServer();
    NodeServer serverB = new NodeServer();
    try {/* www .  j av a2 s .  co m*/
        serverA.initialize("127.0.0.1", 8042, bossGroup, workerGroup, messageRegistry,
                new ChannelInboundHandlerAdapter());
        serverB.initialize("127.0.0.1", 8042, bossGroup, workerGroup, messageRegistry,
                new ChannelInboundHandlerAdapter());
    } finally {
        serverA.shutdown();
        serverB.shutdown();
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}