处理拆包粘包

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