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.mpush.netty.http.NettyHttpClient.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);/*from   www . j  av a2s .  co  m*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}

From source file:com.mpush.netty.server.NettyServer.java

License:Apache License

private void createServer(final Listener listener, EventLoopGroup boss, EventLoopGroup work,
        Class<? extends ServerChannel> clazz) {
    /***//  www .  ja va  2 s. c om
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channel(clazz);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        ChannelFuture f = b.bind(port).sync().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    Logs.Console.error("server start success on:{}", port);
                    if (listener != null)
                        listener.onSuccess(port);
                } else {
                    Logs.Console.error("server start failure on:{}", port, future.cause());
                    if (listener != null)
                        listener.onFailure(future.cause());
                }
            }
        });
        if (f.isSuccess()) {
            serverState.set(State.Started);
            /**
             * socket
             */
            f.channel().closeFuture().sync();
        }

    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    } finally {
        /***
         * 
         */
        stop(null);
    }
}

From source file:com.mpush.netty.server.NettyTCPServer.java

License:Apache License

private void createServer(Listener listener, EventLoopGroup boss, EventLoopGroup work,
        ChannelFactory<? extends ServerChannel> channelFactory) {
    /***/*from   w  ww. jav  a 2s.  c om*/
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channelFactory(channelFactory);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<Channel>() { // (4)
            @Override
            public void initChannel(Channel ch) throws Exception {//?
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        b.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                serverState.set(State.Started);
                logger.info("server start success on:{}", port);
                if (listener != null)
                    listener.onSuccess(port);
            } else {
                logger.error("server start failure on:{}", port, future.cause());
                if (listener != null)
                    listener.onFailure(future.cause());
            }
        });
    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    }
}

From source file:com.mpush.test.client.ConnClientBoot.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    ServiceDiscoveryFactory.create().syncStart();
    CacheManagerFactory.create().init();

    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)//
            .option(ChannelOption.TCP_NODELAY, true)//
            .option(ChannelOption.SO_REUSEADDR, true)//
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60 * 1000)
            .option(ChannelOption.SO_RCVBUF, 5 * 1024 * 1024).channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
        @Override/*from  ww  w. j ava  2 s .  c om*/
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new PacketDecoder());
            ch.pipeline().addLast("encoder", PacketEncoder.INSTANCE);
            ch.pipeline().addLast("handler", new ConnClientChannelHandler());
        }
    });

    listener.onSuccess();
}

From source file:com.my.netty.object.ObjectEchoClient.java

License:Apache License

public void run() throws Exception {
    Bootstrap b = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  w w w .ja  v  a  2  s. c o m
        b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ObjectEncoder())
                                .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                .addLast(new ObjectEchoClientHandler(firstMessageSize));
                    }
                });

        // Start the connection attempt.
        System.out.println("client prepare connect");
        ChannelFuture f1 = b.connect(host, port).sync();
        ChannelFuture f2 = b.connect(host, port).sync();

        f1.channel().closeFuture().sync();
        f2.channel().closeFuture().sync();
    } finally {
        System.out.println("client do finally");
        workerGroup.shutdownGracefully();
        System.out.println("client closing");
    }
}

From source file:com.my.netty.object.ObjectEchoServer.java

License:Apache License

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

        // Bind and start to accept incoming connections.
        System.out.println("server prepare staring");
        b.bind(port).sync().channel().closeFuture().sync();
        System.out.println("server start ok");
    } finally {
        System.out.println("server  do finally");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        System.out.println("server closing ok");
    }
}

From source file:com.mycompany.ffserver.FFServer.java

@Override
public void run() {
    FFDevice ff_device;//from w w  w .  j a v  a2 s . com
    FFRequest ff_request;
    int dev_count;
    int req_count;

    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            device_lst.add(new FFDevice(ch));
            logger.info("have a new connnection");
        }
    });
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        bootstrap.bind(port).sync();
    } catch (InterruptedException ex) {
        logger.error(ex.getMessage());
    }

    ResultSet rs;
    try {
        rs = DbUtils.getDeviceList();
        String reg_str;
        while (rs.next()) {
            reg_str = rs.getString("regs");
            addRegDevice(reg_str);
            DbUtils.updateAllToOffline();
        }
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (SQLException ex) {
        logger.error(ex.getMessage());
    }

    while (!m_stop_flag) {

        dev_count = device_lst.size();

        for (int i = dev_count - 1; i >= 0; i--) {
            ff_device = (FFDevice) device_lst.get(i);

            if (ff_device.isClosed()) {
                device_lst.remove(i);
                logger.info(String.format("remove device with reg_str '%s' from device_lst",
                        ff_device.getRegStr()));
                continue;
            }

            if (ff_device.getRegStr().isEmpty()) {
                if (ff_device.connect_time + 5000 < System.currentTimeMillis()) {
                    ff_device.Close();
                    logger.info("close connection of un-reg device");
                }
                continue;
            }

            if (!dev_info.isAvailable(ff_device.getRegStr())) {
                ff_device.Close();
                logger.info(String.format("close old connection of device that have reg_str '%s'",
                        ff_device.getRegStr()));
                continue;
            }

            dev_info.lockRegStr(ff_device.getRegStr());

            req_count = req_lst.size();
            for (int j = 0; j < req_count; j++) {
                ff_request = req_lst.get(j);
                if (ff_request.reg_str.equals(ff_device.getRegStr()) && ff_device.req == null) {
                    logger.info(String.format("send req to %s", ff_device.getRegStr()));
                    ff_device.req = ff_request;
                    req_lst.remove(j);
                    break;
                }
            }

            ff_device.Process();
        }

        dev_info.freeAllRegStr();

        try {
            Thread.sleep(10);
        } catch (InterruptedException ex) {
            logger.error(ex.getMessage());
        }
    }
}

From source file:com.mylearn.netty.sample.websocket.client.WebSocketClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   w  w  w.jav  a 2 s  .c  om
        Bootstrap b = new Bootstrap();
        String protocol = uri.getScheme();
        if (!"ws".equals(protocol)) {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        HttpHeaders customHeaders = new DefaultHttpHeaders();
        customHeaders.add("MyHeader", "MyValue");

        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders));

        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("http-codec", new HttpClientCodec());
                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                pipeline.addLast("ws-handler", handler);
            }
        });

        System.out.println("WebSocket Client connecting");
        Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        handler.handshakeFuture().sync();

        // Send 10 messages and wait for responses
        System.out.println("WebSocket Client sending message");
        for (int i = 0; i < 10; i++) {
            ch.writeAndFlush(new TextWebSocketFrame("Message #" + i));
        }

        // Ping
        System.out.println("WebSocket Client sending ping");
        ch.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));

        // Close
        System.out.println("WebSocket Client sending close");
        ch.writeAndFlush(new CloseWebSocketFrame());

        // WebSocketClientHandler will close the connection when the server
        // responds to the CloseWebSocketFrame.
        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.nanxiaoqiang.test.netty.protocol.demo1.client.NettyClient.java

License:Apache License

public void connect(int port, String host) throws Exception {

    // ?NIO//from  www .  java 2 s. c o  m

    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 NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    }
                });
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port)// ,
        // new InetSocketAddress(NettyConstant.LOCALIP,
        // NettyConstant.LOCAL_PORT)
        ).sync();
        // future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:com.nanxiaoqiang.test.netty.protocol.demo1.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*  www.  j a  v a  2 s.  c o  m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    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 IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));// ?
                    ch.pipeline().addLast(new NettyMessageEncoder());// ?
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));// ??
                    ch.pipeline().addLast(new LoginAuthRespHandler());// 
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());// 
                }
            });

    // ???
    ChannelFuture cf = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT);
    cf.channel().closeFuture().sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}