Example usage for io.netty.channel ChannelDuplexHandler ChannelDuplexHandler

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

Introduction

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

Prototype

ChannelDuplexHandler

Source Link

Usage

From source file:MultiThreadClient.java

License:Apache License

public void run() throws Exception {
    try {/*from   w  w w  .j  a  va  2  s.c  om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelDuplexHandler() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println(
                                index + "-??:" + msg + "Read:" + Thread.currentThread());
                    }

                    @Override
                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                            throws Exception {
                        ChannelFuture future = ctx.writeAndFlush(msg, promise);
                        System.out.println(index + "-Write:" + Thread.currentThread());
                        Thread.yield();
                        Thread.yield();
                        future.addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                System.out.println(index + "-Listener" + "Lintener:"
                                        + Thread.currentThread());
                            }
                        });
                    }
                });

        // Make the connection attempt.
        ChannelFuture f = b.connect(host, port).sync();
        for (int i = 0; i < 10; i++) {
            f.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[10]));
        }
        // Wait until the connection is closed.

        f.channel().closeFuture();
    } finally {
        //group.shutdownGracefully();
    }
}

From source file:at.yawk.accordion.netty.NettyConnection.java

License:Mozilla Public License

/**
 * Initialize this channel so messages can be read.
 *///from   w  ww. j  a v a 2s. com
void init() {
    channel.pipeline().addLast(new Framer()).addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            messageHandler.accept((ByteBuf) msg);
        }
    }).addLast(new ChannelDuplexHandler() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            exceptionHandler.accept(cause);
        }

        @Override
        public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
            disconnectHandler.run();
        }
    });
}

From source file:at.yawk.dbus.protocol.DbusConnectorTest.java

@Test(enabled = false)
public void testServer() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(EpollServerDomainSocketChannel.class);
    bootstrap.group(new EpollEventLoopGroup());
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override//from   w w w .  jav a2  s .com
        protected void initChannel(Channel ch) throws Exception {

            ch.pipeline().addLast(new CommandCodec()).addLast(new ChannelDuplexHandler() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof NegotiateUnixFd) {
                        ch.writeAndFlush(new Error("error"));
                    }

                    if (msg instanceof Begin) {
                        ch.pipeline().addLast(new LoggingInboundAdapter())
                                .addLast(new DbusMainProtocol(new MessageConsumer() {
                                    @Override
                                    public boolean requireAccept(MessageHeader header) {
                                        return true;
                                    }

                                    @Override
                                    public void accept(DbusMessage message) {
                                        DbusMessage response = new DbusMessage();

                                        MessageHeader header = new MessageHeader();
                                        header.setMessageType(MessageType.ERROR);
                                        header.addHeader(HeaderField.REPLY_SERIAL,
                                                BasicObject.createUint32(message.getHeader().getSerial()));
                                        //header.addHeader(HeaderField.SIGNATURE, SignatureObject.create(
                                        //        Collections.singletonList(BasicType.VARIANT)));
                                        header.addHeader(HeaderField.ERROR_NAME,
                                                BasicObject.createString("Error"));
                                        response.setHeader(header);

                                        MessageBody body = new MessageBody();
                                        //body.add(VariantObject.create(BasicObject.createString("testing!")));
                                        response.setBody(body);

                                        ch.writeAndFlush(response);
                                    }
                                }));
                        ch.pipeline().remove((Class) getClass());
                        ch.pipeline().remove(CommandCodec.class);
                    }
                }
            });
            ch.writeAndFlush(new Ok(UUID.randomUUID()));
        }
    });
    bootstrap.bind(new DomainSocketAddress(new File("test")));

    try {
        DbusUtil.callCommand(("dbus-send --address=unix:path=" + new File(".").getAbsolutePath()
                + "/test --dest=org.freedesktop.UPower --print-reply "
                + "/org/freedesktop/UPower/devices/DisplayDevice org.freedesktop.DBus.Properties.Get string:org"
                + ".freedesktop.UPower.Device string:State").split(" "));
    } catch (Exception e) {
        e.printStackTrace();
    }
    TimeUnit.DAYS.sleep(1);
}

From source file:chat.viska.xmpp.NettyTcpSession.java

License:Apache License

@SchedulerSupport(SchedulerSupport.CUSTOM)
@Override//  w  w w  . j  a  v a 2s .com
protected Completable openConnection(final Compression connectionCompression,
        final Compression tlsCompression) {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(nettyEventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel channel) throws SSLException {
            if (getConnection().getTlsMethod() == Connection.TlsMethod.DIRECT) {
                tlsHandler = TLS_CONTEXT_BUILDER.build().newHandler(channel.alloc());
                channel.pipeline().addLast(PIPE_TLS, tlsHandler);
            } else {
                channel.pipeline().addLast(PIPE_TLS, new ChannelDuplexHandler());
            }
            channel.pipeline().addLast(PIPE_COMPRESSOR, new ChannelDuplexHandler());
            channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_STANZA_SIZE_BYTE, false, false,
                    Unpooled.wrappedBuffer(">".getBytes(StandardCharsets.UTF_8))));
            channel.pipeline().addLast(new StreamClosingDetector());
            channel.pipeline().addLast(PIPE_DECODER_XML, new XmlDecoder());
            channel.pipeline().addLast(new SimpleChannelInboundHandler<XmlDocumentStart>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final XmlDocumentStart msg)
                        throws Exception {
                    if (!"UTF-8".equalsIgnoreCase(msg.encoding())) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.UNSUPPORTED_ENCODING,
                                "Only UTF-8 is supported in XMPP stream."));
                    }
                }
            });
            channel.pipeline().addLast(new StreamOpeningDetector());
            channel.pipeline().addLast(new XmlFrameDecoder(MAX_STANZA_SIZE_BYTE));
            channel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final String msg)
                        throws Exception {
                    try {
                        feedXmlPipeline(preprocessInboundXml(msg));
                    } catch (SAXException ex) {
                        sendError(new StreamErrorException(StreamErrorException.Condition.BAD_FORMAT));
                    }
                }
            });
            channel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
            channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
                }

                @Override
                public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
                    if (cause instanceof Exception) {
                        triggerEvent(new ExceptionCaughtEvent(NettyTcpSession.this, (Exception) cause));
                    } else {
                        throw new RuntimeException(cause);
                    }
                }
            });
        }
    });

    final ChannelFuture channelFuture = bootstrap.connect(getConnection().getDomain(),
            getConnection().getPort());
    return Completable.fromFuture(channelFuture).andThen(Completable.fromAction(() -> {
        this.nettyChannel = (SocketChannel) channelFuture.channel();
        nettyChannel.closeFuture().addListener(it -> changeStateToDisconnected());
    }));
}

From source file:co.marcin.novaguilds.impl.versionimpl.v1_8.PacketExtensionImpl.java

License:Open Source License

@Override
public void registerPlayer(final Player player) {
    Channel c = getChannel(player);
    ChannelHandler handler = new ChannelDuplexHandler() {
        @Override/*from ww  w . ja  v  a 2 s.c om*/
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg == null) {
                return;
            }

            super.write(ctx, msg, promise);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            try {
                if (msg == null) {
                    return;
                }

                PacketReceiveEvent event = callEvent(new PacketReceiveEvent(msg, player));

                if (event.isCancelled() || event.getPacket() == null) {
                    return;
                }
                super.channelRead(ctx, event.getPacket());
            } catch (Exception e) {
                super.channelRead(ctx, msg);
            }
        }
    };

    ChannelPipeline cp = c.pipeline();
    if (cp.names().contains("packet_handler")) {
        if (cp.names().contains("NovaGuilds")) {
            cp.replace("NovaGuilds", "NovaGuilds", handler);
        } else {
            cp.addBefore("packet_handler", "NovaGuilds", handler);
        }
    }
}

From source file:com.tesora.dve.tools.libmy.AsyncExample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    final String mysqlHost = "localhost";
    final int mysqlPort = 3307;
    final String username = "root";
    final String password = "password";
    final boolean isClearText = true;

    final InetSocketAddress serverAddress = new InetSocketAddress(mysqlHost, mysqlPort);

    final MyBackendDecoder.CharsetDecodeHelper charsetHelper = constructCharsetDecodeHelper();
    final SimpleCredentials cred = constructCredentials(username, password, isClearText);
    final JavaCharsetCatalog javaCharsetCatalog = constructJavaCharsetCatalog();
    final MysqlClientAuthenticationHandler authHandler = new MysqlClientAuthenticationHandler(cred,
            ClientCapabilities.DEFAULT_PSITE_CAPABILITIES, javaCharsetCatalog, new AtomicReference<Charset>());

    final NioEventLoopGroup connectionEventGroup = new NioEventLoopGroup(1);
    final Bootstrap mysqlBootstrap = new Bootstrap();
    mysqlBootstrap // .group(inboundChannel.eventLoop())
            .channel(NioSocketChannel.class).group(connectionEventGroup)
            .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<Channel>() {
                @Override/* w w w .j a v a2 s  .c o  m*/
                protected void initChannel(Channel ch) throws Exception {

                    ch.pipeline().addLast(authHandler).addLast(MyBackendDecoder.class.getSimpleName(),
                            new MyBackendDecoder(charsetHelper)).addLast(new ChannelDuplexHandler() {

                                @Override
                                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                        throws Exception {
                                    System.out.println("WRITE:" + msg);
                                    super.write(ctx, msg, promise);
                                }

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (msg instanceof MyFieldPktResponse) {
                                        final MyFieldPktResponse myFieldPktResponse = (MyFieldPktResponse) msg;
                                        System.out.println("COLUMN: " + myFieldPktResponse.getOrig_column()
                                                + "," + myFieldPktResponse.getColumn_type());
                                    } else if (msg instanceof MyTextResultRow) {
                                        final StringBuilder builder = new StringBuilder();
                                        builder.append("ROW:");
                                        final MyTextResultRow textRow = (MyTextResultRow) msg;
                                        for (int i = 0; i < textRow.size(); i++) {
                                            builder.append('\t');
                                            builder.append(textRow.getString(i));
                                        }
                                        System.out.println(builder.toString());
                                    }
                                    super.channelRead(ctx, msg);
                                }

                                @Override
                                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelInactive(ctx);
                                    System.out.println("CLOSE. ");
                                }
                            });
                }
            });

    final ChannelFuture connectFut = mysqlBootstrap.connect(serverAddress);
    connectFut.sync();
    System.out.println("Waiting to finish authenticate handshake");

    authHandler.assertAuthenticated();//don't write a request until you know the login is complete.

    System.out.println("Connected, and authenticated, getting channel to write requests");

    final Channel chan = connectFut.channel();

    System.out.println("Sending two pipelined requests without blocking for first response.");

    chan.write(MSPComQueryRequestMessage.newMessage("show databases", CharsetUtil.UTF_8));
    chan.write(
            MSPComQueryRequestMessage.newMessage("select * from information_schema.tables", CharsetUtil.UTF_8));
    chan.flush();//NOTE:  nothing is sent until this is called.  Use writeAndFlush if you want it to go out immediately.

    System.out.println("Sleeping 5 sec so all results come back"); //normally you would sync to responses here.
    TimeUnit.SECONDS.sleep(5);
    System.out.println("Closing socket.");
    chan.writeAndFlush(MSPComQuitRequestMessage.newMessage());//send friendly hangup message. Probably correct to also wait for server close or an OK packet.

    chan.close();
    chan.closeFuture().sync();
    System.out.println("Exiting.");
    System.exit(0);
}

From source file:freddo.dtalk2.broker.netty.NettyChannel.java

License:Apache License

public void setIdleTime(int idleTime) {
    if (mContext.pipeline().names().contains("idleStateHandler")) {
        mContext.pipeline().remove("idleStateHandler");
    }// w w  w.  j  av a 2  s . c  o m
    if (mContext.pipeline().names().contains("idleEventHandler")) {
        mContext.pipeline().remove("idleEventHandler");
    }
    mContext.pipeline().addFirst("idleStateHandler", new IdleStateHandler(idleTime, idleTime / 2, 0));
    mContext.pipeline().addAfter("idleStateHandler", "idleEventHandler", new ChannelDuplexHandler() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            LOG.trace(">>> userEventTriggered: {}", evt);
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.READER_IDLE) {
                    LOG.debug("read idle");
                    ctx.close();
                } else if (e.state() == IdleState.WRITER_IDLE) {
                    LOG.debug("write idle");
                    ctx.channel().writeAndFlush(
                            new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
                }
            }
        }
    });
}

From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java

License:Apache License

@Before
public void setup() throws Exception {
    ChannelHandler uncaughtExceptionHandler = new ChannelDuplexHandler() {
        @Override/* ww  w.ja v a  2 s .  co m*/
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            caughtException = cause;
            super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    };

    TsiHandshakerFactory handshakerFactory = new DelegatingTsiHandshakerFactory(
            FakeTsiHandshaker.clientHandshakerFactory()) {
        @Override
        public TsiHandshaker newHandshaker(String authority) {
            return new DelegatingTsiHandshaker(super.newHandshaker(authority)) {
                @Override
                public TsiPeer extractPeer() throws GeneralSecurityException {
                    return mockedTsiPeer;
                }

                @Override
                public Object extractPeerObject() throws GeneralSecurityException {
                    return mockedAltsContext;
                }
            };
        }
    };
    ManagedChannel fakeChannel = NettyChannelBuilder.forTarget("localhost:8080").build();
    ObjectPool<Channel> fakeChannelPool = new FixedObjectPool<Channel>(fakeChannel);
    LazyChannel lazyFakeChannel = new LazyChannel(fakeChannelPool);
    ChannelHandler altsServerHandler = new ServerAltsProtocolNegotiator(handshakerFactory, lazyFakeChannel)
            .newHandler(grpcHandler);
    // On real server, WBAEH fires default ProtocolNegotiationEvent. KickNH provides this behavior.
    ChannelHandler handler = new KickNegotiationHandler(altsServerHandler);
    channel = new EmbeddedChannel(uncaughtExceptionHandler, handler);
}

From source file:io.grpc.alts.internal.AltsProtocolNegotiatorTest.java

License:Apache License

@Test
public void flushShouldFailAllPromises() throws Exception {
    doHandshake();/* w w w .ja v a 2 s  .c  o  m*/

    channel.pipeline().addFirst(new ChannelDuplexHandler() {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            throw new Exception("Fake exception");
        }
    });

    // Write the message 1 character at a time.
    String message = "hello";
    final AtomicInteger failures = new AtomicInteger();
    for (int ix = 0; ix < message.length(); ++ix) {
        ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8);
        @SuppressWarnings("unused") // go/futurereturn-lsc
        Future<?> possiblyIgnoredError = channel.write(in).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    failures.incrementAndGet();
                }
            }
        });
    }
    channel.flush();

    // Verify that the promises fail.
    assertEquals(message.length(), failures.get());
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java

License:Apache License

@Test
public void uncaughtException_closeAtMostOnce() throws Exception {
    final AtomicInteger closes = new AtomicInteger();
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelDuplexHandler() {
                @Override/*from  ww w.j a v  a  2  s  .  co  m*/
                public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
                    closes.getAndIncrement();
                    // Simulates a loop between this handler and the WriteBufferingAndExceptionHandler.
                    ctx.fireExceptionCaught(Status.ABORTED.withDescription("zap").asRuntimeException());
                    super.close(ctx, promise);
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    chan.connect(addr).sync();
    chan.close().sync();
    assertEquals(1, closes.get());
}