今天遇到一个奇葩问题,以前项目都没遇到过!就是在protobuff里面的int32位标志的数据0~127正常显示,只要大于127数据就变得很大!
搞了整整一天才把这个问题稍微解决!只是稍微解决!记录下备注!其实就是把string改成byte[ ].
客户端使用unity + tolua
服务端使用erlang
网络通信使用protobuff
网络通信unity使用原生的c#编写,其它模块使用lua,包括协议都用lua!网络协议(包头+协议号+压缩码+真正数据body+md5),其中真正数据body就是使用lua的protobuff,其它字段都是原生c#!!!!其实就是把网络层导出接口给lua调用!说下流程就是lua使用protobuff打包数据,发送到c#层进行数据封装在发送到服务端!其中原本lua打包的数据是以string的格式发送到c#层,问题就在这里。
/// <summary>
/// 专门使用在lua发送网络消息
/// </summary>
/// <param name="ProtoID">协议号</param>
/// <param name="Pb_data">内容</param>
public void SendLuaMessage(int ProtoID , byte[] Pb_data)
// public void SendLuaMessage(int ProtoID , string Pb_data)
{
NetMsg_1001 msg = new NetMsg_1001();
msg.Pb_Send_Data = Pb_data;
msg.ProtocolId = (short)ProtoID; //协议ID包含在msg里面
SendMessage(msg);
}
Pb_Send_Data是原本是string类型,经过血的测试发送到erlang服务端出现大于127数变大!改为byte[]正常!感觉是Encoding.UTF8.GetString这个把字节编码改了出现问题,没深究!再修改数据的读取和写入把string改成byte[].例如:
public int WriteByteArr(byte[] bytes, 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);
}
同理服务端发送过来的数据解析也应该解析成byte[],还有个需要注意的地方就是分发到lua的byte[]在tolua里面使用 new LuaByteBuffer进行封装下。
NetMsg_1001 testMsg = message as NetMsg_1001;
// Dispatch<string>(protoId.ToString(), testMsg.Pb_Receive_Data);
Dispatch<LuaByteBuffer>(protoId.ToString(), new LuaByteBuffer(testMsg.Pb_Receive_Data));
/*******************************************************************
* 注意:文件自动生成,不需要手动需改!
* 最后更新时间: 2017-2-22 09:51:23
* 名字: NetMsg_1001
* 简单解析: 网络协议
*******************************************************************/
using System.Collections;
using System.Collections.Generic;
public class NetMsg_1001 : NetMsg
{
//C>>S
// public string Pb_Send_Data ; //Protobuff_Data
public byte[] Pb_Send_Data; //修改成byte[]防止protobuff int32出错
//S>>C
// public string Pb_Receive_Data ; //Protobuff_Data
public byte[] Pb_Receive_Data;
public NetMsg_1001()
{
ProtocolId = 1001;
}
public override string _Type()
{
return typeof(NetMsg_1001).Name;
}
public override void Read(ByteArray buf)
{
base.Read(buf);
// Pb_Receive_Data = buf.ReadString ();
Pb_Receive_Data = buf.ReadByteArr();
}
protected override void WriteMessage(ByteArray buf)
{
Len =
buf.WriteByteArr( Pb_Send_Data );
// buf.WriteByteArr (Pb_Send_Data);
}
}