今年就要过去了,之前的两个月不断熬夜写自己想的东西。年度总结一些。自己这几天一直在造轮子,写一套类似protobuff的东西,就是自定义协议,自动生成客户端服务器端的小东西。调试已经通过。其实就是字节流的操作。其中要主要的就是大小端的问题,还有erlang比特位的使用。也写了个类似NGUI的图集管理。趁着新年也分享下。出去玩几天录一个小视频太多东西要记录了等回来看有神马需要注意和需要修改的。
客户端byteArray.cs 部分代码
public int WriteByte(int value)
{
mDataBuff[mPosition] = (byte)value;
mPosition++;
mLength = mPosition;
CheckBuffSize();
return 1;
}
public int WriteInt(int value)
{
byte[] bytes = BitConverter.GetBytes(value);
EndianReverse(bytes);
Array.Copy(bytes, 0, mDataBuff, mPosition, 4);
mPosition += 4;
mLength = mPosition;
CheckBuffSize();
return 4;
}
public int WriteLong(long value)
{
byte[] bytes = BitConverter.GetBytes(value);
EndianReverse(bytes);
Array.Copy(bytes, 0, mDataBuff, mPosition, 8);
mPosition += 8;
mLength = mPosition;
CheckBuffSize();
return 8;
}
public int WriteFloat(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
EndianReverse(bytes);
Array.Copy(bytes, 0, mDataBuff, mPosition, 4);
mPosition += 4;
mLength = mPosition;
CheckBuffSize();
return 4;
}
public int WriteShort(int value)
{
byte[] bytes = BitConverter.GetBytes((short)value);
EndianReverse(bytes);
Array.Copy(bytes, 0, mDataBuff, mPosition, 2);
mPosition += 2;
mLength = mPosition;
CheckBuffSize();
return 2;
}
public int WriteString(string value, bool isWriteLen = true)
{
byte[] bytes = Encoding.UTF8.GetBytes(value);
int oldPostion = mPosition;
//字符串大小端不用转换,只有字符串的长度需要转换
int strLength = bytes.Length;
Byte[] strLengthBytes = BitConverter.GetBytes(strLength);
EndianReverse(strLengthBytes);
Array.Copy(strLengthBytes, 0, mDataBuff, mPosition, 4);
if (isWriteLen)
mPosition += 4;
Array.Copy(bytes, 0, mDataBuff, mPosition, strLength);
mPosition += strLength;
mLength = mPosition;
CheckBuffSize();
return (int)(mPosition - oldPostion);
}
服务端erlang对应的解析:
%%写入byte
write_byte(Bin,NumByte) ->
<<Bin/binary,NumByte:8/little>>.
%% 写入int
write_int(Bin,NumInt)->
<<Bin/binary,NumInt:32/little>>.
%% 写入字符串
write_string(Bin,Str)->
StrBin = list_to_binary(Str),
L = byte_size(StrBin), %% 数据长度
<<Bin/binary,L:32/little,StrBin/binary>>.
%%写入Long
write_long(Bin,NumLong)->
<<Bin/binary,NumLong:64/little>>.
......
工具一自动生成两套协议代码,现在协议支持int,short,byte,long,string,Array,对象e
http://www.tudou.com/programs/view/dgN9kjzQODw/ 密码:xing