在netty学习02-Netty初步学习-HelloNetty中已经学习了如何搭建netty服务端,下面介绍下如何搭建netty客户端。
netty客户端搭建的流程和服务端类似,很多地方都是把Server缓冲Client即可。
1.创建客户端服务类
ClientBootstrap bootstrap=new ClientBootstrap();
2.创建监听和消息接发的线程池
ExecutorService boss=Executors.newCachedThreadPool(); ExecutorService worker=Executors.newCachedThreadPool();
3.设置服务niosocket工厂,将工厂和监听及读写线程绑定,同时将服务类和工厂绑定
bootstrap.setFactory(new NioClientSocketChannelFactory(boss,worker));
4. 设置管道工厂,将消息处理类放到工厂,消息编码和解码功能加入与否都可以
bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder",new StringDecoder()); pipeline.addLast("encoder",new StringEncoder()); pipeline.addLast("hiHandler",new HiHandler()); return pipeline; } });
5.连接服务端
ChannelFuture connect=bootstrap.connect(new InetSocketAddress("127.0.0.1",10010));
6.获取到通信通道,便可以开始接发消息了
Channel channel=connect.getChannel(); System.out.println("client start"); Scanner scanner=new Scanner(System.in); while (true){ System.out.println("请输入"); channel.write(scanner.next()); }