/// <summary> /// the functions reading the data from socket. /// </summary> private void ReadData(byte[] data) { DebugUtils.Log(DebugUtils.Type.AsyncSocket, "Async tcp socket has received network data, data length " + data.Length); using (ByteStreamReader reader = new ByteStreamReader(data)) { try { int dataLength = data.Length; int startPos = 0; while (startPos < dataLength) { int length = reader.ReadShort(); if (startPos + length > dataLength) { DebugUtils.LogWarning(DebugUtils.Type.AsyncSocket, "Async tcp socket: There are separated packets!"); int separatedLength = dataLength - startPos; unusedBuffer = new byte[separatedLength]; Buffer.BlockCopy(data, startPos, unusedBuffer, 0, separatedLength); break; } short version = reader.ReadShort(); //version == 127 byte[] response = reader.ReadBytes(length - 4); ServerTcpMessage[] messages = ServerTcpMessage.Unpack(response); if (ResponseHandler != null) { ResponseHandler(messages); } startPos += length; } } catch (Exception e) { DebugUtils.LogError(DebugUtils.Type.AsyncSocket, e.ToString()); } } }
public static ServerTcpMessage[] Unpack(/*ServerType serverType,*/ byte[] responseData) { DebugUtils.Assert(responseData != null && responseData.Length > 0, "Response data is null!"); using (ByteStreamReader reader = new ByteStreamReader(responseData)) { long serverId = reader.ReadLong(); ClientTcpMessage.sessionId = reader.ReadInt(); //if sessionId is 4 bytes, that's OK. int msgNum = reader.ReadByte(); ServerTcpMessage[] responseMessages = new ServerTcpMessage[msgNum]; for (int i = 0; i < msgNum; i++) { int len = reader.ReadShort(); int code = reader.ReadInt(); long seq = reader.ReadLong(); if (Enum.IsDefined(typeof(MsgCode), code)) { responseMessages[i] = new ServerTcpMessage((MsgCode)code, seq, reader.ReadBytes(len)); DebugUtils.Log(DebugUtils.Type.Protocol, "Receive network message, protocol code " + code); } else { DebugUtils.LogError(DebugUtils.Type.Protocol, "For now, the client can't recognize the received protocol code " + code); } } return(responseMessages); } }