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:com.friz.audio.AudioServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    AudioServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from   w ww.ja  v a 2s  .c o  m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(HttpServerCodec.class.getName(), new HttpServerCodec());
                    p.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(65536));
                    p.addLast(ChunkedWriteHandler.class.getName(), new ChunkedWriteHandler());
                    p.addLast(AudioChannelHandler.class.getName(), new AudioChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(AudioRequestEvent.class, new AudioRequestEventListener());

    service.startAsync();
}

From source file:com.friz.game.GameServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    GameServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override// www .j  a  v  a2  s  . c o m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LoginInitEncoder.class.getName(), new LoginInitEncoder());
                    p.addLast(LoginInitDecoder.class.getName(), new LoginInitDecoder());
                    p.addLast(GameChannelHandler.class.getName(), new GameChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}

From source file:com.friz.lobby.LobbyServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    LobbyServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*from   ww w  .  j a  v  a2  s . c om*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LobbyInitEncoder.class.getName(), new LobbyInitEncoder());
                    p.addLast(LobbyInitDecoder.class.getName(), new LobbyInitDecoder());
                    p.addLast(LobbyChannelHandler.class.getName(), new LobbyChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    eventHub.listen(LobbyInitRequestEvent.class, new LobbyInitEventListener());
    eventHub.listen(SocialInitRequestEvent.class, new SocialInitEventListener());
    eventHub.listen(CreationRequestEvent.class, new CreationEventListener());
    eventHub.listen(LoginRequestEvent.class, new LoginRequestEventListener());

    moduleHub.listen(ClientVersionModule.class, new ClientVersionModuleListener());
    moduleHub.listen(ClientTypeModule.class, new ClientTypeModuleListener());
}

From source file:com.friz.login.LoginServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    LoginServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override// w  w  w. jav  a  2  s .co m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    p.addLast(LoginChannelHandler.class.getName(), new LoginChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}

From source file:com.friz.owari.network.client.Client.java

License:Open Source License

@Override
public void initialize() throws NoSuchAlgorithmException {
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {

        @Override/*from  w  ww. j av a 2s .  co m*/
        protected void initChannel(NioSocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast(HandshakeEncoder.class.getName(), new HandshakeEncoder());
            pipeline.addLast(HandshakeDecoder.class.getName(), new HandshakeDecoder());
            pipeline.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
            pipeline.addLast(ClientChannelHandler.class.getName(), new ClientChannelHandler(Client.this));
        }

    }).option(ChannelOption.TCP_NODELAY, true);

    hub.listen(HandshakeEvent.class, new HandshakeListener());
    hub.listen(ExchangeRecieveEvent.class, new ExchangeListener());
    hub.listen(PatchInitEvent.class, new PatchInitListener());
    hub.listen(PatchEvent.class, new PatchListener());

    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH");
    keyPairGenerator.initialize(1024);

    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    privateKey = keyPair.getPrivate();
    publicKey = keyPair.getPublic();
}

From source file:com.friz.owari.network.server.Server.java

License:Open Source License

@Override
public void initialize() throws NoSuchAlgorithmException {
    bootstrap = new ServerBootstrap();

    bootstrap.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override// ww w.j  a va 2  s  . c o m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast(HandshakeDecoder.class.getName(), new HandshakeDecoder());
                    pipeline.addLast(HandshakeEncoder.class.getName(), new HandshakeEncoder());
                    pipeline.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    pipeline.addLast(ServerChannelHandler.class.getName(),
                            new ServerChannelHandler(Server.this));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(HandshakeEvent.class, new HandshakeListener());
    hub.listen(ExchangeRecieveEvent.class, new ExchangeListener());

    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH");
    keyPairGenerator.initialize(1024);

    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    privateKey = keyPair.getPrivate();
    publicKey = keyPair.getPublic();
}

From source file:com.friz.update.UpdateServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    UpdateServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from  w  w  w  .  j  av  a  2s  .c om
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(UpdateInitEncoder.class.getName(), new UpdateInitEncoder());
                    p.addLast(UpdateInitDecoder.class.getName(), new UpdateInitDecoder());
                    p.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    p.addLast(UpdateChannelHandler.class.getName(), new UpdateChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(UpdateRequestEvent.class, new UpdateRequestEventListener());
    hub.listen(XorRequestEvent.class, new XorRequestEventListener());
    hub.listen(FileRequestEvent.class, new FileRequestEventListener());

    service.startAsync();
}

From source file:com.gdut.Netty_testing.time_server.client.TimeClient.java

License:Apache License

/**
 * // w  w w .  j  a  v a 2  s  .  c  o m
 * @Title: main
 * @Description: TODO
 * @param @param args
 * @param @throws Exception
 * @return void
 * @throws
 */
public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler(),
                                new TimeOutBoundHandler(), new LoggingHandler(LogLevel.INFO));
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        // channel.connect(remoteAddress, promise);
        // ?connect()??OutboundHandler
        // ?InboundHandlerlogic???
        // ??
        // InboundHandler?writeAndFlush(Object
        // msg)??OutBoundHandler
        // ??  ctx.write(encoded, promise);
        // writeAndFlush(Object msg)
        // ?InboundHandler  decoder?
        // ?TimeClientHandler()Handler,
        // ctx.close();?OutBoundHandler ?

        Thread.sleep(9000);
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java

License:Apache License

/**
 * //from ww w  .  j a va  2 s.c om
 * @Title: main
 * @Description: TODO
 * @param @param args
 * @param @throws Exception
 * @return void
 * @throws
 */
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast(new LoggingHandler(LogLevel.INFO), new TimeEncoder(),
                                new TimeServerHandler());
                        // new TimeEncoder(),
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        f.addListener(new GenericFutureListener<Future<? super Void>>() {

            public void operationComplete(Future<? super Void> future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("success " + future.isSuccess());
            }
        });

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java

License:Apache License

/**
 * Helper method to start the server listening for connections. The
 * server is bound to the port specified by {@link GemFireRedisServer#serverPort}
 * // w  w w.  j ava  2s. c om
 * @throws IOException
 * @throws InterruptedException
 */
private void startRedisServer() throws IOException, InterruptedException {
    ThreadFactory selectorThreadFactory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet());
            t.setDaemon(true);
            return t;
        }

    };

    ThreadFactory workerThreadFactory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet());
            return t;
        }

    };

    bossGroup = null;
    workerGroup = null;
    Class<? extends ServerChannel> socketClass = null;
    if (singleThreadPerConnection) {
        bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
        workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
        socketClass = OioServerSocketChannel.class;
    } else {
        bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
        workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
        socketClass = NioServerSocketChannel.class;
    }
    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    String pwd = system.getConfig().getRedisPassword();
    final byte[] pwdB = Coder.stringToBytes(pwd);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (logger.fineEnabled())
                logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress());
            ChannelPipeline p = ch.pipeline();
            p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
            p.addLast(ExecutionHandlerContext.class.getSimpleName(),
                    new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB));
        }
    }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize())
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
    if (this.logger.infoEnabled()) {
        String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort
                + "}, Selector threads: " + this.numSelectorThreads;
        if (this.singleThreadPerConnection)
            logMessage += ", One worker thread per connection";
        else
            logMessage += ", Worker threads: " + this.numWorkerThreads;
        this.logger.info(logMessage);
    }
    this.serverChannel = f.channel();
}