mirror of
https://gitee.com/willfree/min-dev-java.git
synced 2026-06-06 03:19:28 +08:00
在VMSConnection模块中的BC_Encoder类中加入魔数,减少服务器端的内存error
This commit is contained in:
@@ -13,16 +13,23 @@ import java.nio.channels.SocketChannel;
|
||||
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
||||
*/
|
||||
public class BC_Encoder {
|
||||
// 魔数:为了避免读取数据时,因为读错开始的数据长度,而导致后台分配一块巨大的内存,出现内存错误
|
||||
final static int magicNumber = 1803118696; // 后台设定的数字为uint32:0x6b796868
|
||||
// 转为byte[]的魔数。小端字节序,4个字节
|
||||
final static byte[] magicNumberBytes = ByteHelper.int32ToByteArray(magicNumber);
|
||||
|
||||
/**
|
||||
* Encode 将消息编码: 加一个长度头
|
||||
* | 魔数 | length | data |
|
||||
* @param message
|
||||
* @return
|
||||
*/
|
||||
public static byte[] Encode(byte[] message){
|
||||
byte[] length= ByteHelper.int32ToByteArray(message.length);
|
||||
byte[] pkg=new byte[4+ message.length];
|
||||
System.arraycopy(length,0,pkg,0,4);
|
||||
System.arraycopy(message,0,pkg,4,message.length);
|
||||
byte[] pkg=new byte[4+4+ message.length];
|
||||
System.arraycopy(magicNumberBytes,0,pkg,0,4);
|
||||
System.arraycopy(length,0,pkg,4,4);
|
||||
System.arraycopy(message,0,pkg,8,message.length);
|
||||
return pkg;
|
||||
}
|
||||
|
||||
@@ -43,6 +50,26 @@ public class BC_Encoder {
|
||||
}
|
||||
}
|
||||
System.out.println("start read...");
|
||||
// 魔数
|
||||
byte[] magicBuf=new byte[4];
|
||||
try {
|
||||
int revL=channel.socket().getInputStream().read(magicBuf);
|
||||
// channel.read(ByteBuffer.wrap(buf));
|
||||
if(revL<0){
|
||||
System.out.println("magic read len < 0");
|
||||
return null;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
int magicServerNumber=ByteHelper.byteArrayToInt32(magicBuf);
|
||||
System.out.println("read magic number form server: "+magicServerNumber);
|
||||
if(magicServerNumber!=magicNumber){
|
||||
System.out.println("the magic number error: "+magicServerNumber
|
||||
+", it should be "+magicNumber);
|
||||
return null;
|
||||
}
|
||||
// 读取消息的长度
|
||||
byte[] buf=new byte[4];
|
||||
try {
|
||||
@@ -57,7 +84,7 @@ public class BC_Encoder {
|
||||
return null;
|
||||
}
|
||||
int length=ByteHelper.byteArrayToInt32(buf);
|
||||
System.out.println("read 111: "+length);
|
||||
System.out.println("read 111-length: "+length);
|
||||
// 读取真正的消息数据
|
||||
byte[] pkg=new byte[length]; // 最终读取的数据区
|
||||
byte[] cachepkg=new byte[length]; // 缓存数据区
|
||||
@@ -84,7 +111,7 @@ public class BC_Encoder {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
System.out.println("read 222: "+new String(pkg));
|
||||
System.out.println("read 222-pkg: "+new String(pkg));
|
||||
return pkg;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user