Example usage for io.netty.channel ChannelInitializer ChannelInitializer

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

Introduction

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

Prototype

ChannelInitializer

Source Link

Usage

From source file:UdpServer.java

License:Open Source License

public void run() throws Exception {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    //Create Actor System
    final ActorSystem system = ActorSystem.create("CapwapFSMActorSystem");
    final ActorRef PacketProcessorActor = system
            .actorOf(Props.create(CapwapMsgProcActor.class, "MessageProcessorActor"), "MessageProcessorActor");
    try {// w w  w.ja v  a2  s.c  o m
        final Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        createActorAndHandler(p);
                        //p.addLast(new IncommingPacketHandler(PacketProcessorActor));
                    }
                });

        // Bind and start to accept incoming connections.
        Integer pPort = port;
        InetAddress address = InetAddress.getLoopbackAddress();
        System.out.printf("\n\nwaiting for message %s %s\n\n", String.format(pPort.toString()),
                String.format(address.toString()));
        b.bind(address, port).sync().channel().closeFuture().await();

    } finally {
        System.out.print("In Server Finally");
    }
}

From source file:NettyServer.java

License:Open Source License

void start() throws Exception {
    parentGroup = new NioEventLoopGroup(1);
    childGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap().group(parentGroup, childGroup)
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  w  w  w . jav  a  2 s  .c  o  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();

                    pipeline.addLast("lineFrame", new LineBasedFrameDecoder(256));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("encoder", new StringEncoder());

                    pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            Channel channel = ctx.channel();
                            channelActiveHandler.accept(channel);
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            messageConsumer.accept(msg);
                        }
                    });
                }
            });
    channel = bootstrap.bind(port).channel();
    System.out.println("NettyServer started");
}

From source file:FSMTester.java

License:Open Source License

public void run() throws Exception {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    //Create Actor System
    final ActorSystem system = ActorSystem.create("CapwapFSMActorSystem");
    final ActorRef PacketProcessorActor = system
            .actorOf(Props.create(CapwapMsgProcActor.class, "MessageProcessorActor"), "MessageProcessorActor");
    try {//from ww w. j  a  v  a  2s  . c om
        final Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new IncommingPacketFSMHandler(PacketProcessorActor));
                    }
                });

        // Bind and start to accept incoming connections.
        Integer pPort = port;
        InetAddress address = InetAddress.getLoopbackAddress();
        System.out.printf("\n\nwaiting for message %s %s\n\n", String.format(pPort.toString()),
                String.format(address.toString()));
        b.bind(address, port).sync().channel().closeFuture().await();

    } finally {
        System.out.print("In Server Finally");
    }
}

From source file:afred.javademo.proxy.rpc.ObjectEchoClient.java

License:Apache License

public void start(String host, int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   www .j  av  a 2 s  . com*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
        });

        channel = b.connect(host, port).sync().channel();
    } finally {

    }
}

From source file:afred.javademo.proxy.rpc.ObjectEchoServer.java

License:Apache License

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

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w ww .j  a  v a 2 s.c  o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ObjectEchoServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(8080).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:alluxio.client.netty.NettyClient.java

License:Apache License

/**
 * Creates and returns a new Netty client bootstrap for clients to connect to remote servers.
 *
 * @param handler the handler that should be added to new channel pipelines
 * @return the new client {@link Bootstrap}
 *///from   w  ww.  j  a v  a 2 s  . c om
public static Bootstrap createClientBootstrap(final ClientHandler handler) {
    final Bootstrap boot = new Bootstrap();

    boot.group(WORKER_GROUP).channel(CLIENT_CHANNEL_CLASS);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    boot.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(RPCMessage.createFrameDecoder());
            pipeline.addLast(ENCODER);
            pipeline.addLast(DECODER);
            pipeline.addLast(handler);
        }
    });

    return boot;
}

From source file:alluxio.network.netty.NettyClient.java

License:Apache License

/**
 * Creates and returns a new Netty client bootstrap for clients to connect to remote servers.
 *
 * @param address the socket address/*from  www. j  a  v a2  s  .  c o  m*/
 * @return the new client {@link Bootstrap}
 */
public static Bootstrap createClientBootstrap(SocketAddress address) {
    final Bootstrap boot = new Bootstrap();

    boot.group(WORKER_GROUP).channel(
            NettyUtils.getClientChannelClass(NettyUtils.CHANNEL_TYPE, !(address instanceof InetSocketAddress)));
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    if (NettyUtils.CHANNEL_TYPE == ChannelType.EPOLL) {
        boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    }

    // After 10 missed heartbeat attempts and no write activity, the server will close the channel.
    final long timeoutMs = Configuration.getMs(PropertyKey.NETWORK_NETTY_HEARTBEAT_TIMEOUT_MS);
    final long heartbeatPeriodMs = Math.max(timeoutMs / 10, 1);
    boot.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(RPCMessage.createFrameDecoder());
            pipeline.addLast(ENCODER);
            pipeline.addLast(DECODER);
            pipeline.addLast(new IdleStateHandler(0, heartbeatPeriodMs, 0, TimeUnit.MILLISECONDS));
            pipeline.addLast(new IdleWriteHandler());
        }
    });

    return boot;
}

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

License:Mozilla Public License

/**
 * Initialize this server so connections can be accepted (does not bind!).
 *//* w w  w.  j  ava  2  s. co  m*/
void init() {
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            NettyConnection connection = new NettyConnection(ch);
            connection.init();
            connectionHandler.accept(connection);
        }
    });
}

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

public DbusConnector() {
    bootstrap = new Bootstrap();
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override//from w w  w .jav  a2 s  .c  om
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAutoRead(false);
        }
    });
}

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  . ja  v a2  s . c  om
        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);
}