netty java client_JAVA(7)-netty-client

客户端也就4步,上代码

public void client() throws Exception {

//1.创建管道和管理

EventLoopGroup workerGroup =new NioEventLoopGroup(1);

Bootstrap b=new Bootstrap();

b.group(workerGroup);

//2.设置类型

b.channel(NioSocketChannel.class);

//3.管道建立好了,初始化

b.handler(new ChannelInitializer(){

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

channel=socketChannel;

socketChannel.pipeline().addLast(new MyHandler());

}

});

ChannelFuture future= b.connect("localhost",8888).sync();

//等待关闭

future.channel().closeFuture().sync();

System.out.println("go on");

workerGroup.shutdownGracefully();

}

myhandler 用来处理读写

static class MyHandler extends ChannelInboundHandlerAdapter

{

//1.读

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

//2.Object msg->String str

//readableBytes()长度,readerIndex()起始位置

ByteBuf buf=null;

try {

buf = (ByteBuf) msg;

byte[] bytes = new byte[buf.readableBytes()];//

buf.getBytes(buf.readerIndex(), bytes);

String str = new String(bytes);

ClientFrame.INSTANCE.updateText(str);

}finally //任何情况都要释放

{

if(buf!=null)

ReferenceCountUtil.release(buf);

}

}

//异常

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

super.exceptionCaught(ctx, cause);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值