大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。
一个、Netty解决TCP协议的数据分包的想法
+—–+—–+—–+
发送数据是: | ABC | DEF | GHI |
+—–+—–+—–+
LengthFieldBasedFrameDecoder ,它的原理是server端和client约定一个协议格式:数据包=协议长度+协议体
| 协议长度部分(接收数据长度) | 协议体部分(要接收的数据)|
int
maxFrameLength:定义接收数据包的最大长度,假设发送的数据包超过此值。则抛出异常;
lengthFieldOffset:长度属性部分的偏移值,0表示长度属性位于数据包头部。
lengthFieldLength:长度属性的字节长度,假设设置为4,就是我们用4个字节存放数据包的长度;
int
lengthAdjustment:协议体长度调节值,修正信息长度,假设设置为4,那么解码时再向后推4个字节。
int
initialBytesToStrip:跳过字节数,如我们想跳过长度属性部分。
public byte[] send(byte[] sendData) throws UnknownHostException, IOException {
Socket socket = new Socket(serverIp, serverPort);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
byte resultArray[] = null;
try {
// 定义一个发送消息协议格式:|--header:4 byte--|--content:10MB--|
// 获取一个4字节长度的协议体头
byte[] dataLength = intToByteArray(4, sendData.length);
// 和请求的数据组成一个请求数据包
byte[] requestMessage = combineByteArray(dataLength, sendData);
//发送数据-------------------------------
os.write(requestMessage);
os.flush();
//接收数据-------------------------------
resultArray = IOUtils.toByteArray(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
os.close();
is.close();
socket.close();
}
return resultArray;
}
private static byte[] intToByteArray(int byteLength, int intValue) {
return ByteBuffer.allocate(byteLength).putInt(intValue).array();
}
private static byte[] combineByteArray(byte[] array1, byte[] array2) {
byte[] combined = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, combined, 0, array1.length);
System.arraycopy(array2, 0, combined, array1.length, array2.length);
return combined;
}
Netty服务端:定义一个LengthFieldBasedFrameDecoder(1024*1024*1024, 0, 4,0,4))。最大数据量是1GB,长度属性位于数据包头部,占4个字节,协议体调节值为0,跳过头部协议长度四个字节
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framedecoder",new LengthFieldBasedFrameDecoder(1024*1024*1024, 0, 4,0,4));
pipeline.addLast(new TCPServiceHandler());// 处理业务Handler
}
三、总结:client和服务端定义消息格式必须一致
版权声明:本文博客原创文章。博客,未经同意,不得转载。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/117147.html原文链接:https://javaforall.net
