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(); }
其中注释那两段一定不能调用,只有在彻底不用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(); } }
最后三行是很重要的,因为channel 写进通道以后sync 才会将其发送出去。
先写这么多吧。
时间: 2024-10-12 06:38:59