Netty 4.0.27多重チャネルを取得

1816 ワード

  EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(new InetSocketAddress(host, port));
            b.handler(new ChannelInitializer<SocketChannel>() {

                public void initChannel(SocketChannel ch) throws Exception {
                	ch.pipeline().addLast(new StringDecoder());
                	//ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new EchoClientHandler());
                }
            });
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.TCP_NODELAY, true);
            ChannelFuture f = b.connect().sync();
            channel=f.channel();
            f.addListener(new ChannelFutureListener() {

                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()){
                        System.out.println("client connected");
                    }else{
                        System.out.println("server attemp failed");
                        future.cause().printStackTrace();
                    }
                }
            });

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

このうち注釈の2つのセグメントは必ず呼び出すことができず、channelを完全に使わないときだけ呼び出す.
得られたchannelを用いてデータを送信する:
for(int k=0;k<100000;k++){
	    	ChannelFuture cfu=c.channel.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!"+k, CharsetUtil.UTF_8));
	    	if(cfu!=null){
	    		cfu.sync();
	    	}
    	}

最後の3行はチャネルにチャネルを書くとsyncが送信するので重要です.
先にこんなに書きましょう.