netty socket 客服端编程

package com.ming.netty.nio;
 2 
 3 import io.netty.bootstrap.Bootstrap;  4 import io.netty.channel.ChannelFuture;  5 import io.netty.channel.ChannelInitializer;  6 import io.netty.channel.ChannelOption;  7 import io.netty.channel.EventLoopGroup;  8 import io.netty.channel.nio.NioEventLoopGroup;  9 import io.netty.channel.socket.SocketChannel; 10 import io.netty.channel.socket.nio.NioSocketChannel; 11 12 /** 13  * netty 客户端模拟 14  * @author mingge 15  * 16 */ 17 public class TimeClient { 18 19 20 public static void main(String[] args) throws Exception{ 21 new TimeClient().connect("127.0.0.1", 8400); 22  } 23 24 public void connect(String addr,int port) throws Exception{ 25 EventLoopGroup group=new NioEventLoopGroup(); 26 try { 27 Bootstrap b=new Bootstrap(); 28 b.group(group).channel(NioSocketChannel.class) 29 .option(ChannelOption.TCP_NODELAY, true) 30 .handler(new ChannelInitializer<SocketChannel>() { 31 public void initChannel(SocketChannel ch) throws Exception{ 32 ch.pipeline().addLast(new TimeClientHandler()); 33  } 34  }); 35 ChannelFuture f=b.connect(addr,port); 36 f.channel().closeFuture().sync();//等待客户端关闭连接 37 } catch (Exception e) { 38 // TODO: handle exception 39 }finally{ 40  group.shutdownGracefully(); 41  } 42  } 43 }
复制代码
复制代码
 1 package com.ming.netty.nio;
 2 
 3 import io.netty.buffer.ByteBuf;  4 import io.netty.buffer.Unpooled;  5 import io.netty.channel.ChannelHandlerAdapter;  6 import io.netty.channel.ChannelHandlerContext;  7  8 public class TimeClientHandler extends ChannelHandlerAdapter {  9 10 private final ByteBuf byteMsg; 11 12 public TimeClientHandler() { 13 byte[] req="我是请求数据哦".getBytes(); 14 byteMsg=Unpooled.buffer(req.length); 15  byteMsg.writeBytes(req); 16  } 17 18  @Override 19 public void channelActive(ChannelHandlerContext ctx) throws Exception { 20  ctx.writeAndFlush(byteMsg); 21  } 22 23  @Override 24 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 25 ByteBuf buf=(ByteBuf)msg; 26 byte[] req=new byte[buf.readableBytes()]; 27  buf.readBytes(req); 28 String body=new String(req,"GBK"); 29 System.out.println("body:"+body); 30  } 31 32  @Override 33 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 34 //释放资源 35  ctx.close(); 36  } 37 38 39 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值