客户端也就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<SocketChannel>(){
@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);
}
}