处理拆包粘包

This commit is contained in:
wenc000 2020-08-02 23:16:57 +08:00
parent b67523690f
commit f210d8a1e6
2 changed files with 26 additions and 8 deletions

View File

@ -20,5 +20,17 @@ public interface ISocketConst {
* 客户端密码
*/
String CLIENT_SECRET = "clientSecret";
/**
* 异常类
*/
String EXCEPTION_CLASS = "exceptionClass";
/**
* 异常名称
*/
String EXCEPTION_MESSAGE = "exceptionName";
/**
* 异常内容
*/
String EXCEPTION_CONTENT = "exceptionContent";
}

View File

@ -1,5 +1,7 @@
package com.cm.socket.decoder;
import com.cm.socket.enums.SocketMessageEnum;
import com.cm.socket.enums.SocketTypeMessageEnum;
import com.cm.socket.pojo.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
@ -8,6 +10,8 @@ import io.netty.util.CharsetUtil;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* When you feel like quitting. Think about why you started
@ -38,14 +42,18 @@ public class MessageDecoder extends ByteToMessageDecoder {
byte type = in.readByte();
int tokenBytesLength = in.readInt();
int contentBytesLength = in.readInt();
if (in.readableBytes() < contentBytesLength) {
in.resetReaderIndex();
return;
}
String token = getToken(in, tokenBytesLength);
String content = getContent(in, contentBytesLength);
Message message = new Message();
message.setStart(start);
message.setType(type);
message.setToken(token);
message.setContent(content);
out.add(message);
Message tempMessage = new Message();
tempMessage.setStart(start);
tempMessage.setType(type);
tempMessage.setToken(token);
tempMessage.setContent(content);
out.add(tempMessage);
}
/**
@ -59,7 +67,6 @@ public class MessageDecoder extends ByteToMessageDecoder {
return null;
}
if (in.readableBytes() < tokenBytesLength) {
in.resetReaderIndex();
return null;
}
byte[] tokenBytes = new byte[tokenBytesLength];
@ -78,7 +85,6 @@ public class MessageDecoder extends ByteToMessageDecoder {
return null;
}
if (in.readableBytes() < contentBytesLength) {
in.resetReaderIndex();
return null;
}
byte[] contentBytes = new byte[contentBytesLength];