Example usage for io.netty.channel ChannelFuture channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Returns a channel where the I/O operation associated with this future takes place.

Usage

From source file:com.study.hc.net.netty.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure the server.
    // EventLoopGroup   accept NioEventLoop
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    // EventLoopGroup   I/O
    EventLoopGroup workerGroup2 = new NioEventLoopGroup(1);
    try {//from  w  w  w . j  av  a 2 s.  c  o  m
        // ??
        ServerBootstrap b = new ServerBootstrap();
        // ???reactor???
        b.group(bossGroup, workerGroup2).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoServerHandler());
                    }
                });
        // bind??
        ChannelFuture f = b.bind(PORT).sync();
        // ??
        f.channel().closeFuture().sync();
    } finally {
        // 
        bossGroup.shutdownGracefully();
        workerGroup2.shutdownGracefully();
    }
}

From source file:com.supermy.im.netty.TCPServer.java

License:Apache License

/**
 * 3??/*from   ww  w.  j  a  v  a 2 s.c  om*/
 */
protected void doBind() {
    if (closed) {
        return;
    }

    serverBootstrap.bind(tcpPort).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (f.isSuccess()) {
                System.out.println("Started Tcp Server: " + tcpPort);
            } else {
                System.out.println("Started Tcp Server Failed: " + tcpPort);

                // f.channel().eventLoop().schedule(() -> doBind(), 3, TimeUnit.SECONDS);

                f.channel().eventLoop().schedule(new Runnable() {
                    @Override
                    public void run() {
                        doBind();
                    }
                }, 3, TimeUnit.SECONDS);
            }
        }
    });
}

From source file:com.system.distribute.server.FileClient.java

License:Apache License

public ChannelFuture run() throws Exception {
    // Configure the server.
    final Bootstrap bootstrap = BootstrapFactory.createBootstrap(ChannelType.NIO);

    bootstrap.handler(new FileClientHandler());
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);

    try {//from w w w .j  av  a 2  s.  c  om
        final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync();
        channelFuture.awaitUninterruptibly();

    } catch (InterruptedException e) {

    }

    // Start the server.
    ChannelFuture f = bootstrap.bind(port).sync();

    // Wait until the server socket is closed.
    f.channel().closeFuture().sync();
    return f;

}

From source file:com.system.distribute.server.FileServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from ww w . ja  v a  2  s .c om
        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 {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(8192), new StringDecoder(CharsetUtil.UTF_8),
                                new FileHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // 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.tc.websocket.server.handler.ProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    ByteBuf buf = (ByteBuf) msg;//from   w w  w.  j  a v  a  2  s. c  o  m
    String data = new String(ByteBufUtil.getBytes(buf));
    ByteBuf bufData = buf;

    if (Config.getInstance().isEncrypted() && data.contains(StringCache.HTTP)) {
        data = data.replace(StringCache.HTTP, StringCache.HTTPS);
        bufData = Unpooled.wrappedBuffer(data.getBytes());
    }

    //ProxyFrontendHandler.writeToFile("backend", ByteBufUtil.getBytes(bufData));

    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read();

            } else {
                future.channel().close();
            }
        }
    });

}

From source file:com.tc.websocket.server.handler.ProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    this.handler = new ProxyBackendHandler(inboundChannel);

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()).handler(this.handler)
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();

    f.addListener(new ChannelFutureListener() {
        @Override/*from   w  w  w.  ja  v a2 s  .co m*/
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();

            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:com.tc.websocket.server.handler.ProxyFrontendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {

    ByteBuf buf = (ByteBuf) msg;/*  w w w.  j a  v  a  2s .c om*/
    String data = new String(ByteBufUtil.getBytes(buf));

    if (data.contains(Const.UPGRADE_WEBSOCKET) || data.contains(Const.GET_WEBSOCKET)) {
        proxy.set(false);

    } else if (data.contains(StringCache.HTTP_1_1)) {
        proxy.set(true);
    }

    if (proxy.get() == false) {
        writeToFile("frontend." + ctx.channel().id(), ByteBufUtil.getBytes(buf));
    }

    if (Config.getInstance().isCertAuth()) {
        SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get("ssl");
        try {
            X509Certificate cert = sslhandler.engine().getSession().getPeerCertificateChain()[0];
            Principal p = cert.getSubjectDN();

            /* Added by Miguel */
            LdapName ldapDN = new LdapName(p.getName());
            String username = "";
            String thumbprint = getThumbPrint(cert.getEncoded());

            for (Rdn rdn : ldapDN.getRdns()) {
                //System.out.println(rdn.getType() + " -> " + rdn.getValue());
                if (rdn.getType().equals("CN")) {
                    username = rdn.getValue().toString();
                    break;
                }
            }
            /* End Added by Miguel*/

            String sessionId = parseSessionID(data);

            if (sessionId != null) {
                String current = System.getProperty("user.dir");
                //System.out.println("Current working directory in Java : " + current);

                //File sessionFile = new File("c:/sessions/" + sessionId + ".txt");
                File sessionFile = new File(current + "/data/sessions/" + sessionId + ".txt");

                //only write the file if it hasn't been written yet.
                if (sessionFile.createNewFile()) {
                    FileUtils.write(sessionFile, p.getName().replaceAll("\"", "").replaceAll("\\+", ",") + "\n"
                            + username + "\n" + thumbprint);
                }
            }

        } catch (Exception e) {
            LOG.log(Level.SEVERE, null, e);
        }
    }

    if (proxy.get()) {
        ctx.channel().config().setAutoRead(false);
        if (outboundChannel.isActive()) {
            outboundChannel.writeAndFlush(buf).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {
                        // was able to flush out data, start to read the next chunk
                        ctx.channel().read();
                    } else {
                        future.channel().close();
                    }
                }
            });
        }
    } else {
        //make sure the backend handler knows its a websocket connection.
        this.handler.setWebsocket(true);

        //get handle on the pipeline.
        ChannelPipeline pipeline = ctx.pipeline();

        //apply the websocket handlers
        builder.apply(pipeline);

        //remove this handler.
        pipeline.remove(this);

        //fire the event to move on to the next handler.
        ctx.fireChannelRead(msg);
    }

}

From source file:com.tcy.app.netty4.Ne4Client.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/* w w  w .  j ava2  s. c  o m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new Ne4ClientHandler(firstMessageSize));

        // Make the connection attempt.
        ChannelFuture f = b.connect(host, port).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.tencent.mars.proxy.ProxyServer.java

License:Open Source License

public void start() throws Exception {
    try {//from  www. j a v  a  2s. c o  m
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(channelHandler).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        channelFuture.channel().closeFuture().sync();
    } catch (Exception e) {

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.tesora.dve.parlb.MysqlClientHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .handler(new LoadBalancerServerHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(peServerAddress);
    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override//w  w  w . ja  v  a  2s . com
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}