/// <summary> /// 以前 4 个字节作为头部协议号 /// </summary> /// <param name="message"></param> /// <param name="msgId"></param> /// <returns></returns> public static byte[] GetSendBytes(object message, int msgId) { byte[] messageBytes = serializer.Serialize(message); var tempBytes = BitConverter.GetBytes(msgId); byte[] msgIdBytes = tempBytes.GetHeadBytes(); byte[] finalBytes = BytesPool.Take(4 + messageBytes.Length); for (int i = 0; i < 4; i++) { finalBytes[i] = msgIdBytes[i]; } for (int i = 0; i < messageBytes.Length; i++) { finalBytes[i + 4] = messageBytes[i]; } return(finalBytes); }
public byte[] Handle(byte[] receiveBytes) { // todo var bytes = BytesPool.Take(receiveBytes.Length + 4); //var bytes = new byte[receiveBytes.Length + 4]; var lengthBytes = BitConverter.GetBytes(receiveBytes.Length); for (int i = 0; i < 4; i++) { bytes[i] = lengthBytes[3 - i]; } for (int i = 0; i < receiveBytes.Length; i++) { bytes[i + 4] = receiveBytes[i]; } return(bytes); }
/// <summary> /// 接收消息分发方法,在 Unity FixedUpdate 中调用 /// </summary> private void MessageDispatch() { foreach (var channel in netModule.ChannelDic.Values) { if (channel.MessageStorage.ReceiveCount == 0) { continue; } for (int i = 0; i < channel.MessageStorage.ReceiveCount; i++) { var bytes = channel.MessageStorage.GetReceiveMessage(); var messageIdBytes = bytes.GetHeadBytes(); var messageId = BitConverter.ToInt32(messageIdBytes, 0); var messageBodyLength = bytes.Length - 4; var finalBytes = BytesPool.Take(messageBodyLength); Buffer.BlockCopy(bytes, 4, finalBytes, 0, messageBodyLength); BytesPool.Restore(bytes); InvokeRespHandler(messageId, finalBytes); } } }