netty学习03-Netty客户端和服务端结合

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());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值