Unity3d使用ToLua lua protobuf3配合java neety protobuf3包含源码

Odessa ·
更新时间:2024-11-14
· 628 次阅读

博主环境(所有文件都在最底下):

Unity环境: 2018.1.0b11(64bit) java环境:jdk 1.8, netty环境:netty-all-4.1.16.Final.jar protobuf环境:protobuf-java-3.3.0 python环境:python 2.7

网络协议:

使用简单的协议一段完整的数据,前4位byte是数据总长度,向后偏移4位是protoId,用于指向解析的protoBytes

JAVA解析数据的地方:

文件:NioServerHandler.java protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // TODO Auto-generated method stub ByteBuf buf=(ByteBuf) msg; int totalByteLen = buf.readableBytes(); int indeLne = 0; //解包 while(totalByteLen>indeLne) { buf.readBytes(dataLenBytes,0,4); int totalLen = Utils.bytesToInt(dataLenBytes, 0); indeLne += 4; buf.readBytes(dataLenBytes,0,4); int protoId = Utils.bytesToInt(dataLenBytes, 0); indeLne += 4; byte[]protoData = new byte[totalLen - 8]; buf.readBytes(protoData,0,totalLen-8); indeLne += totalLen-8; Utils.Parse(protoId, protoData); } /*** * readBytes这个方法的三个参数分别是:(1)复制目标地址,(2)起始位置注意这里的起始位置如果写0,他就是0+你上次读取的位置,(3)复制数据长度 * */ } //这是Utils里面的方法 public static void Parse(int protoId,byte[] protoData) { try { if(protoId == 1001) { Person person = Person.parseFrom(protoData); System.out.println("\n解析成功:\n"+person.toString()); } }catch (Exception e) { e.printStackTrace(); } }

Lua处理解析数据和发送加密protobuffer数据的地方:

--接收数据 function NetWork.Receive(data) local protoId = data:GetProtoId() local luaBytes = data:ReadBuffer() local pbName = UNITY.CMD2PB[protoId].name local pbData = pb.decode(pbName, luaBytes) GameNetManager:sendNetMessage(protoId,pbData) --测试发送 local personData = { name = "ilse", age = 18, contacts = { { name = "alice", phonenumber = 12312341234 }, { name = "bob", phonenumber = 45645674567 } } } NetWork.SendProtoData(1001,personData) local datac =0 end --发送数据 function NetWork.SendProtoData(protoId,data) local pbName = UNITY.CMD2PB[protoId].name local bytes = assert(pb.encode(pbName, data)) local ByteBuffer = GameByteBuffer.getNewInstance() ByteBuffer:WriteBuffer(protoId,bytes) local gameSoketClient = GameSoketClient.GetInstance() gameSoketClient:WriteGameByteBuffer(ByteBuffer) end

C#处理数据的地方:

文件:GameSoketClient.cs void OnReceive(byte[] bytes, int length) { // Array.Reverse(bytes, 0, length); //拆包处理分包,协议是最前面4位是总长度,然后偏移4位是protoid,最后是protoData int resolveLen = 0; while (resolveLen<length) { //数据段大小 int size = BitConverter.ToInt32(bytes, 0); resolveLen += 4; //protoId int protoId = BitConverter.ToInt32(bytes, resolveLen); resolveLen += 4; // int prptoDataSize = size - 4 - 4; //数据 GameByteBuffer ByteBuffer = GameByteBuffer.getNewInstance(); ByteBuffer.ParseByteBuffer(ref bytes, resolveLen, prptoDataSize, protoId); ReceiveBytesQueue.Enqueue(ByteBuffer); resolveLen += prptoDataSize; } }

最后我们来看看运行结果:

你可能需要的源代码(注意所有的源码和工具都有说明,请先看下载说明):

ToLua集成Protobuffer3

Protobuf-3.3生成器PB和java资源.zip

Netty Protobuf3 测试服务器

集成Protobuffer3到ToLua


作者:一路随云00000



JAVA protobuf unity3d unity 源码

需要 登录 后方可回复, 如果你还没有账号请 注册新账号