、
下面的代码 实现的 是 第二种 length包括了请求头
自己学习的时候,网上的文章层次不齐,错误很多,下面的代码都是自己多次调试,并且亲自实验的代码,保证正确。
消息体:
package edu.mi.tcp;
import java.util.Arrays;
public class MessageProtocol {
private int headler;
private int len;
private int msg;
private String content;
public int getHeadler() {
return headler;
}
public void setHeadler(int headler) {
this.headler = headler;
}
public int getMsg() {
return msg;
}
public void setMsg(int msg) {
this.msg = msg;
}
public int getLen() {
return len+12;
}
public void setLen(int len) {
this.len = len;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "MessageProtocol{" +
"len=" + len +
", content=" + content +
'}';
}
}
自定义的解码器:MyDeconder
package edu.mi.tcp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* 继承对应的ByteToMessageDecoder 字节转化为对应的消息类型 并解决对应的 分包 问题 ,
* 并对分包进行粘包
*/
public class MyDeconder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//需要将获取到的二进制字节码转成MyMessageProtocol数据包(对象)
//进行解码
/**
* 标记对应的bytebuf开始位置
* 因为有可能当前的包大小不足一个实体类,被截取了,
* 此时需要等待后续的数据到来 并且 要把readIndex进行对应的复位
*/
int beginReader;
/**
* 代表当前可以读的字节的数量
* 假如能读的数量 连一个int字节的长度都没有 不进行读取 因为标识报文长度都没有
*/
int i = in.readableBytes();
if (i > 12) {
//记录当前的 byteBuf开始的位置 因为后续可能复位
beginReader = in.readerIndex();
System.out.println("beginReader"+beginReader);
System.out.println("decoder 可读数量"+i);
//记录开始位置
in.markReaderIndex();
//读取前四个字节 length的长度
int headler = in.readInt();
System.out.println("decoder被调用" + headler);
//读过长度后 还剩下多少字节 因为有可能当前对应被分包了
int len=in.readInt();
System.out.println("decoder被调用len" + len);
/**
* 去掉请求头中的 长度
*/
len=len-12;
int msg=in.readInt();
int z = in.readableBytes();
System.out.println("decoder 可读数量"+z);
//看看剩下的字节长度是不是 有对应的 标记位的长度大
if(z<len){
//没有 代表 被分包了, 复位byteBuf 不进行读取 等待后续数据到来
in.readerIndex(beginReader);
return;
}
//代表可以进行读取了哦
System.out.println("decoder 可读数量"+z);
//生成对应的 len长度的字节 接取数据
byte[] bytes = new byte[len];
//读到 buff 字节中,并且对应的readIndex 移动
in.readBytes(bytes);
int o = in.readableBytes();
System.out.println("decoder 可读数量"+o);
//封装成MessageProtocol对象 放入out 传给下一个handler进行业务处理
MessageProtocol messageProtocol = new MessageProtocol();
messageProtocol.setHeadler(headler);
messageProtocol.setMsg(msg);
messageProtocol.setLen(len);
messageProtocol.setContent(new String(bytes));
//添加到对应的list中 供后续使用,并且进行粘包
out.add(messageProtocol);
} else {
return;
}
}
}
自定义的编码器:
package edu.mi.tcp;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;
/**
* 编码器 把对应的 对应变为对应的字节对象
*/
public class MyEncoder extends MessageToByteEncoder<MessageProtocol> {
@Override
protected void encode(ChannelHandlerContext ctx, MessageProtocol messageProtocol, ByteBuf out) throws Exception {
System.out.println("encoder被调用"+messageProtocol.getLen());
out.writeInt(messageProtocol.getHeadler());
/**
*
*/
out.writeInt(messageProtocol.getLen());
out.writeInt(messageProtocol.getMsg());
/**
* 内容紧跟其后
*/
out.writeBytes(messageProtocol.getContent().getBytes());
int i = out.readableBytes();
System.out.println(i);
}
}
TcpClient
package edu.mi.tcp;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
public class TcpClient {
public static String HOST = "127.0.0.1";
public static int PORT = 9999;
public static Bootstrap bootstrap = getBootstrap();
public static Channel channel = getChannel(HOST,PORT);
/**
* 初始化Bootstrap
* @return
*/
public static final Bootstrap getBootstrap(){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
//pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("frameDecoder", new MyDeconder());
pipeline.addLast("frameEncoder", new MyEncoder());
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new TcpClientHandler());
}
});
b.option(ChannelOption.SO_KEEPALIVE, true);
return b;
}
public static final Channel getChannel(String host,int port){
Channel channel = null;
try {
channel = bootstrap.connect(host, port).sync().channel();
} catch (Exception e) {
e.printStackTrace();
System.out.println("连接Server(IP[%s],PORT[%s])失败");
return null;
}
return channel;
}
public static void sendMsg(String msg) throws Exception {
if(channel!=null){
MessageProtocol messageProtocol=new MessageProtocol();
messageProtocol.setContent(msg);
messageProtocol.setLen(msg.getBytes().length);
messageProtocol.setHeadler(120);
messageProtocol.setMsg(520);
// ByteBuf echo = Unpooled.directBuffer();
channel.writeAndFlush(messageProtocol).sync();
}else{
System.out.println("消息发送失败,连接尚未建立!");
}
}
public static void main(String[] args) throws Exception {
try {
long t0 = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
if(i%3==0){
TcpClient.sendMsg("11111111aaa111在去找个i不过111");
}else if(i%3==1){
TcpClient.sendMsg("22222222asdasdssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss2222222aaa222222222aaaaa2在去找啊啊个i不过2222");
}else if(i%3==2){
TcpClient.sendMsg("33在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找在去找3333333333333333sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss333333sss3333aaaaaa3在去找2sdaskdjajdalsjd个i不过33333");
}
}
long t1 = System.nanoTime();
System.out.println((t1-t0)/1000000.0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
TcpClientHandler
package edu.mi.tcp;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class TcpClientHandler extends ChannelHandlerAdapter {
public TcpClientHandler() {
}
//private byte[] req;
/**
* 链路链接成功
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
/*for (int i = 0; i < 1000; i++) {
ctx.writeAndFlush("1ac");
} */
// 链接成功后发送
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("client收到数据" +msg);
// ctx.write("收到数据!");
// ctx.write(msg);
// ctx.write("w2d");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
TcpServer
package edu.mi.tcp;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
public class TcpServer {
private static final String IP = "127.0.0.1";
private static final int PORT = 9999;
/**用于分配处理业务线程的线程组个数 */
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; //默认
/** 业务出现线程大小*/
protected static final int BIZTHREADSIZE = 4;
/*
* NioEventLoopGroup实际上就是个线程池,
* NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
* 每一个NioEventLoop负责处理m个Channel,
* NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
*/
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
protected static void run() throws Exception {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
/**
* 参数示意:网上很多解释都是错误的
*
* 第一个参数maxFrameLength 代表最大的字节长度
*
* lengthFieldOffset: 请求头偏移数量 因为 有可能你的length字段并不是第一个字段 有可能第二个字段才是代表了 长度字段
* 所以这个表示了 length字段前面字段长度
*
* lengthFieldLength :代表字段能够接收的最大长度 和maxFrameLength 区别是 这个是实际长度 lengthFieldLength这个是限制的长度
*
* lengthAdjustment:补偿值 用于计算 从长度的字段 lengthFieldLength 到 content 内容区域的 距离
*
* initialBytesToStrip: 需要跳过的字段长度 因为有的时候 我们不关注请求头(或者内容) 可以直接跳过 不传给下一个 处理器
* 假如我们还是关注对应的请求头的 我们就要把对应的字段 保留 不进行跳过
*
*
*
*/
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 4, -8, 12));
// pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
// pipeline.addLast( new MyDeconder());
pipeline.addLast( new MyEncoder());
//pipeline.addLast( new MyEncoder());
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new TcpServerHandler());
}
});
// b.bind(IP, PORT).sync();
ChannelFuture f = b.bind(PORT).sync(); // (7)
f.channel().closeFuture().sync();
System.out.println("TCP服务器已启动");
}
protected static void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
public static void main(String[] args) throws Exception {
System.out.println("开始启动TCP服务器");
TcpServer.run();
// TcpServer.shutdown();
}
}
TcpServerHandler
package edu.mi.tcp;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class TcpServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
MessageProtocol messageProtocol = new MessageProtocol();
String s = "33我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊3333333333333333sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss中国333333sss3333aaaaaa3在去找2sdaskdjajdalsjd个i不过3333333我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊我的天啊3333333333333333sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss中国333333sss3333aaaaaa3在去找2sdaskdjajdalsjd个i不过3333333333333333333333ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss333333sss3333aaaaaa3在去找2sdaskdjajdalsjd个i不过333333333333333333333sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss333333sss3333aaaaaa3在去找2sdaskdjajdalsjd个i不过33333";
messageProtocol.setLen(s.getBytes().length);
messageProtocol.setContent(s);
messageProtocol.setHeadler(12);
messageProtocol.setMsg(10);
ctx.write(messageProtocol); // (1)
System.out.println("访问数据" + msg);
// ctx.write(obj); // (1)
ctx.flush(); // (2)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close theconnection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
//ctx.writeAndFlush("有客户端连接"); // (3)
}
}