public override void Deserialize(IPacketHeader packetHeader, MemoryStream sourceStream) { sourceStream.Read(m_Buffer, 0, packetHeader.PacketLength - 1); MyString = Encoding.ASCII.GetString(m_Buffer, 0, packetHeader.PacketLength - 1); sourceStream.Read(m_Buffer, 0, 1); MyBoolean = BitConverter.ToBoolean(m_Buffer, 0); }
/// <summary> /// 反序列化消息包。 /// </summary> /// <param name="packetHeader">消息包头。</param> /// <param name="source">要反序列化的来源流。</param> /// <param name="customErrorData">用户自定义错误数据。</param> /// <returns>反序列化后的消息包。</returns> public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { customErrorData = null; CTM_SCPacketHeader header = packetHeader as CTM_SCPacketHeader; if (header == null) { Log.Warning("Packet header is invalid."); return(null); } Packet packet = null; if (header.IsValid) { Type packetType = GetServerToClientPacketType(header.Id); if (packetType != null && source is MemoryStream) { packet = (Packet)ProtobufHelper.FromStream(ReferencePool.Acquire(packetType), (MemoryStream)source); } else { Log.Warning("Can not deserialize packet for packet id '{0}'.", header.Id.ToString()); } } else { Log.Warning("Packet header is invalid."); } ReferencePool.Release(header); return(packet); }
/// <summary> /// 反序列化消息包。 /// </summary> /// <param name="packetHeader">消息包头。</param> /// <param name="source">要反序列化的来源流。</param> /// <param name="customErrorData">用户自定义错误数据。</param> /// <returns>反序列化后的消息包。</returns> public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { // 注意:此函数并不在主线程调用! customErrorData = null; SCPacketHeader scPacketHeader = packetHeader as SCPacketHeader; if (scPacketHeader == null) { Log.Warning("Packet header is invalid."); return(null); } Packet packet = null; if (scPacketHeader.IsValid) { Type packetType = GetServerToClientPacketType(scPacketHeader.Id); if (packetType != null) { packet = (Packet)RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, ReferencePool.Acquire(packetType), packetType, PrefixStyle.Fixed32, 0); } else { Log.Warning("Can not deserialize packet for packet id '{0}'.", scPacketHeader.Id.ToString()); } } else { Log.Warning("Packet header is invalid."); } ReferencePool.Release(scPacketHeader); return(packet); }
public static Packet DeserializePacket(IPacketHeader packetHeader, Stream source /*, out object customErrorData*/) { ET_CSPacketHeader header = packetHeader as ET_CSPacketHeader; if (header == null) { Debug.LogError("header为空."); return(null); } Packet packet = null; if (header.IsValid) { Type packetType = GetClientToServerPacketType(header.Id); if (packetType != null && source is MemoryStream) { object instance = Activator.CreateInstance(packetType); packet = (Packet)ProtobufHelper.FromStream(instance, (MemoryStream)source); } else { Debug.LogError("Can not deserialize packet for packet id '{0}'.", header.Id.ToString()); } } else { Debug.LogError("Packet header is invalid."); } header.Clear(); return(packet); }
public bool ProcessPacketHeader(ClientSocket clientSocket) { try { IPacketHeader packetHeader = ET_NetworkChannelHelper.DeserializePacketHeader(clientSocket.ReceiveState.Stream); if (packetHeader == null) { string errorMessage = "Packet header is invalid."; Debug.LogError(errorMessage); throw new Exception(errorMessage); } clientSocket.ReceiveState.PrepareForPacket(packetHeader); if (packetHeader.PacketLength <= 0) //一般不会满足 { return(ProcessPacket(clientSocket)); } } catch (Exception exception) { Debug.LogError(exception); throw; } return(true); }
public void PrepareForPacket(IPacketHeader packetHeader) { if (packetHeader == null) { throw new GameFrameworkException("Packet header is invalid."); } Reset(packetHeader.PacketLength, packetHeader); }
private void Reset(int targetlength, IPacketHeader packetHeader) { if (targetlength < 0) { } m_Stream.Position = 0L; m_Stream.SetLength(targetlength); m_PacketHeader = PacketHeader; }
/// <inheritdoc /> public async Task <int> WriteHeaderAsync(IPacketHeader header) { //We only need to serialize and then write byte[] bytes = Serializer.Serialize(header); await DecoratedClient.WriteAsync(bytes) .ConfigureAwait(false); return(bytes.Length); }
public virtual async Task <NetworkIncomingMessage <TReadPayloadBaseType> > ReadAsync(CancellationToken token) { IPacketHeader header = null; TReadPayloadBaseType payload = null; using (await readSynObj.LockAsync(token).ConfigureAwait(false)) { //Check crypto first. We may need to decrypt this header //This is very complicated though for reading server headers //since they do not have a constant size header = await BuildHeaderWithDecryption(token) .ConfigureAwait(false); //If the header is null it means the socket disconnected if (header == null) { return(null); } //if was canceled the header reading probably returned null anyway if (token.IsCancellationRequested) { return(null); } //We need to read enough bytes to deserialize the payload await ReadAsync(PacketPayloadReadBuffer, 0, header.PayloadSize, token) .ConfigureAwait(false); //TODO: Should we timeout? //Opcode will still be encrypted if crypto is enabled so we must decryt that too if (CryptoService.isInitialized) { CryptoService.DecryptionService.ProcessBytes(PacketPayloadReadBuffer, 0, 2, PacketPayloadReadBuffer, 0); } //If the token was canceled then the buffer isn't filled and we can't make a message if (token.IsCancellationRequested) { return(null); } Console.WriteLine($"Server Debug OpCode: {(NetworkOperationCode)PacketPayloadReadBuffer.Reinterpret<ushort>()}:{PacketPayloadReadBuffer.Reinterpret<short>()}"); //Console.ReadKey(); //Deserialize the bytes starting from the begining but ONLY read up to the payload size. We reuse this buffer and it's large //so if we don't specify the length we could end up with an issue. payload = Serializer.Deserialize <TReadPayloadBaseType>(PacketPayloadReadBuffer, 0, header.PayloadSize); } Console.WriteLine($"Server Read Client Write Debug: {payload.GetType()}"); return(new NetworkIncomingMessage <TReadPayloadBaseType>(header, payload)); }
private void Reset(int targetLength, IPacketHeader packetHeader) { if (targetLength < 0) { throw new GameFrameworkException("Target length is invalid."); } m_Stream.Position = 0L; m_Stream.SetLength(targetLength); m_PacketHeader = packetHeader; }
private bool ProcessPacketHeader() { try { object customErrorData = null; IPacketHeader packetHeader = m_NetworkChannelHelper.DeserializePacketHeader(m_ReceiveState.Stream, out customErrorData); if (customErrorData != null) { if (NetworkChannelCustomError != null) { NetworkChannelCustomError(this, customErrorData); } } if (packetHeader == null) { string errorMessage = "Packet header is invalid."; if (NetworkChannelError != null) { NetworkChannelError(this, NetworkErrorCode.DeserializePacketHeaderError, errorMessage); return(false); } throw new Exception(errorMessage); } if (packetHeader.PacketLength > 0) { m_ReceiveState.PrepareForPacket(packetHeader.PacketLength); } else { m_ReceiveState.PrepareForPacketHeader(m_NetworkChannelHelper.PacketHeaderLength); } } catch (System.Exception exception) { m_Active = false; if (NetworkChannelError != null) { NetworkChannelError(this, NetworkErrorCode.DeserializePacketHeaderError, exception.ToString()); return(false); } throw; } return(true); }
/// <summary> /// Creates a new incoming message envelope. Represents a complete /// logical packet including the header and the deserialized payload. /// </summary> /// <param name="header"></param> /// <param name="payload">The payload.</param> public NetworkIncomingMessage(IPacketHeader header, TPayloadType payload) { if (header == null) { throw new ArgumentNullException(nameof(header)); } if (payload == null) { throw new ArgumentNullException(nameof(payload)); } Header = header; Payload = payload; }
protected virtual bool ProcessPacketHeader() { try { object customErrorData = null; IPacketHeader packetHeader = m_NetworkChannelHelper.DeserializePacketHeader(m_ReceiveState.Stream, out customErrorData); if (customErrorData != null && NetworkChannelCustomError != null) { NetworkChannelCustomError(this, customErrorData); } if (packetHeader == null) { string errorMessage = "Packet header is invalid."; if (NetworkChannelError != null) { NetworkChannelError(this, NetworkErrorCode.DeserializePacketHeaderError, SocketError.Success, errorMessage); return(false); } throw new GameFrameworkException(errorMessage); } m_ReceiveState.PrepareForPacket(packetHeader); if (packetHeader.PacketLength <= 0) { bool processSuccess = ProcessPacket(); m_ReceivedPacketCount++; return(processSuccess); } } catch (Exception exception) { m_Active = false; if (NetworkChannelError != null) { SocketException socketException = exception as SocketException; NetworkChannelError(this, NetworkErrorCode.DeserializePacketHeaderError, socketException != null ? socketException.SocketErrorCode : SocketError.Success, exception.ToString()); return(false); } throw; } return(true); }
public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { customErrorData = null; MOMsg msg = null; try { var buffer = new byte[packetHeader.PacketLength]; source.Read(buffer, 0, buffer.Length); msg = MOMsg.Parser.ParseFrom(ByteString.CopyFrom(buffer)); } catch (Exception ex) { customErrorData = ex.Message; } return(new MOPacket(msg)); }
public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { customErrorData = null; SCPacketHeader scPacketHeader = packetHeader as SCPacketHeader; if (scPacketHeader == null) { Log.Warning("Packet header is invalid."); return(null); } Packet packet = null; if (scPacketHeader.IsValid) { if (scPacketHeader.Id == 4) { //BinaryReader r = new BinaryReader(source); //byte[] message = r.ReadBytes((int)(source.Length - source.Position)); //string returnStr = string.Empty; //for (int i = 0; i < message.Length; i++) //{ // returnStr += message[i].ToString("X2"); //} SCData scData = SCData.Create(); ((DataResponse)scData.GetExtensionObject()).MergeFrom(source); //Log.Info("data response {0}", scData); packet = scData; } else { packet = SCHeartBeat.Create(); Log.Info("heart response "); } } else { Log.Warning("Packet header is invalid."); } ReferencePool.Release(scPacketHeader); return(packet); }
/// <inheritdoc /> public async Task WriteAsync(TWritePayloadBaseType payload) { //Serializer the payload first so we can build the header byte[] payloadData = Serializer.Serialize(payload); IPacketHeader header = PacketHeaderFactory.Create(payload, payloadData); //VERY critical we lock here otherwise we could write a header and then another unrelated body could be written inbetween using (await writeSynObj.LockAsync().ConfigureAwait(false)) { //It's important to always write the header first await HeaderReaderWriter.WriteHeaderAsync(header) .ConfigureAwait(false); //Write the outgoing message, it will internally create the header and it will be serialized await DecoratedClient.WriteAsync(payloadData) .ConfigureAwait(false); } }
public GameFramework.Network.Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { var ret = new Q3Packet(); try { byte[] bytes = new byte[packetHeader.PacketLength]; source.Read(bytes, 0, packetHeader.PacketLength); ret.SetArgs(bytes); } catch (Exception ex) { Log.Error(ex); } customErrorData = null; return(ret); }
public async Task <NetworkIncomingMessage <TReadPayloadBaseType> > ReadAsync(CancellationToken token) { IPacketHeader header = null; TReadPayloadBaseType payload = null; using (await readSynObj.LockAsync(token).ConfigureAwait(false)) { //Read the header first header = await HeaderReaderWriter.ReadHeaderAsync(token) .ConfigureAwait(false); //If the header is null it means the socket disconnected if (header == null) { return(null); } //if was canceled the header reading probably returned null anyway if (token.IsCancellationRequested) { return(null); } //We need to read enough bytes to deserialize the payload await ReadAsync(PacketPayloadReadBuffer, 0, header.PayloadSize, token) .ConfigureAwait(false); //TODO: Should we timeout? //If the token was canceled then the buffer isn't filled and we can't make a message if (token.IsCancellationRequested) { return(null); } //WARNING: We must do deserialization inside of the lock otherwise we can encounter a race condition //Deserialize the bytes starting from the begining but ONLY read up to the payload size. We reuse this buffer and it's large //so if we don't specify the length we could end up with an issue. payload = Serializer.Deserialize <TReadPayloadBaseType>(PacketPayloadReadBuffer, 0, header.PayloadSize); } return(new NetworkIncomingMessage <TReadPayloadBaseType>(header, payload)); }
public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { customErrorData = null; ET_SCPacketHeader header = packetHeader as ET_SCPacketHeader; if (header == null) { Log.Warning("Packet header is invalid."); return(null); } Packet packet = null; if (header.IsValid) { Type packetType = GetServerToClientPacketType(header.Id); //Log.Debug("~~~~~~~~~~~"+packetType.Name); if (packetType != null && source is MemoryStream) { //packet = (Packet)RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, ReferencePool.Acquire(packetType), packetType, PrefixStyle.Fixed32, 0); object instance = Activator.CreateInstance(packetType); //packet = (Packet)ProtobufHelper.FromStream(packetType, (MemoryStream)source); packet = (Packet)ProtobufHelper.FromStream(instance, (MemoryStream)source); } else { Log.Warning("Can not deserialize packet for packet id '{0}'.", header.Id.ToString()); } } else { Log.Warning("Packet header is invalid."); } ReferencePool.Release(header); //DispatchMsg(packet); return(packet); }
public async Task <NetworkIncomingMessage <TReadPayloadBaseType> > ReadAsync(CancellationToken token) { TReadPayloadBaseType payload = null; IPacketHeader header = null; using (await readSynObj.LockAsync(token).ConfigureAwait(false)) { //if was canceled the header reading probably returned null anyway if (token.IsCancellationRequested) { return(null); } //We need to read enough bytes to deserialize the payload payload = await Serializer.DeserializeAsync <TReadPayloadBaseType>(this, token) .ConfigureAwait(false); //TODO: Should we timeout? //Null payload means the socket disconnected if (payload == null) { return(null); } //TODO: Any reasonable way to get the bytes read size so we can use it as the header? //We need to create our own manual header since we aren't reading one //However, we do not know the header size so we should just say it's 0 header = new HeaderlessPacketHeader(0); } //If the token was canceled then the buffer isn't filled and we can't make a message if (token.IsCancellationRequested) { return(null); } return(new NetworkIncomingMessage <TReadPayloadBaseType>(header, payload)); }
/// <summary> /// **GF程序集内部执行 /// 反序列化消息包 /// </summary> /// <param name="packetHeader"></param> /// <param name="source"></param> /// <param name="customErrorData"></param> /// <returns></returns> public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { // 注意:此函数并不在主线程调用! customErrorData = null; SCPacketHeader packetHeaderImpl = packetHeader as SCPacketHeader; if (packetHeaderImpl == null) { Log.Warning("Packet header is null."); return(null); } Packet packet = null; if (packetHeaderImpl.IsValid()) { Type packetType = GetServerToClientPacketType(packetHeaderImpl.Id); if (packetType != null) { packet = (Packet)RuntimeTypeModel.Default.Deserialize(source, ReferencePool.Acquire(packetType), packetType); } else { Log.Warning("Can't deserialize packet id '{0}'.", packetHeaderImpl.Id); } } else { Log.Warning("Packet header is invalid. Id : {0}", packetHeaderImpl.Id); } ReferencePool.Release(packetHeaderImpl); return(packet); }
public Packet Deserialize(IPacketHeader packetHeader, MemoryStream sourceStream) { var packetId = packetHeader.PacketId; PacketBase packet = null; switch (packetId) { case 1: packet = new Packet1(); break; case 2: default: packet = new Packet2(); break; } packet.Deserialize(packetHeader, sourceStream); Log.InfoFormat("[SimpleNetChannelHandler Deserialize] packet={0}", packet); // Recycle packet header. return(packet); }
public abstract void Deserialize(IPacketHeader packetHeader, MemoryStream sourceStream);
public async Task <NetworkIncomingMessage <TReadPayloadBaseType> > ReadAsync(CancellationToken token) { IPacketHeader header = null; TReadPayloadBaseType payload = null; using (await readSynObj.LockAsync(token).ConfigureAwait(false)) { await ReadAsync(PacketPayloadReadBuffer, 0, 6, token) .ConfigureAwait(false); //Check crypto first. We may need to decrypt this header if (CryptoService.isInitialized) { CryptoService.DecryptionService.ProcessBytes(PacketPayloadReadBuffer, 0, 6, PacketPayloadReadBuffer, 0); } OutgoingClientPacketHeader clientHeader = Serializer.Deserialize <OutgoingClientPacketHeader>(PacketPayloadReadBuffer, 0, 6); //TODO: Enable this logging on Debug //Console.WriteLine($"New ClientHeader: OpCode: {clientHeader.OperationCode} PacketSize: {clientHeader.PacketSize} PayloadSize: {clientHeader.PayloadSize}"); header = clientHeader; //Console.WriteLine($"Recieved OpCode: {clientHeader.OperationCode}:{(ushort)clientHeader.OperationCode} from client Encrypted:{CryptoService.isInitialized}"); //If the header is null it means the socket disconnected if (header == null) { return(null); } //if was canceled the header reading probably returned null anyway if (token.IsCancellationRequested) { return(null); } //We need to start reading at 2 bytes so we can manually insert the opcode //into the payload buffer await ReadAsync(PacketPayloadReadBuffer, 2, header.PayloadSize, token) .ConfigureAwait(false); //TODO: Should we timeout? //RACE CONDITION. WE NEED TO LOCK AROUND READING FRM THIS BUFF byte[] reinterpretedOpCode = ((short)clientHeader.OperationCode).Reinterpret(); PacketPayloadReadBuffer[0] = reinterpretedOpCode[0]; PacketPayloadReadBuffer[1] = reinterpretedOpCode[1]; //If the token was canceled then the buffer isn't filled and we can't make a message if (token.IsCancellationRequested) { return(null); } //TODO: Revisit thbis to check if +2 is ok //Deserialize the bytes starting from the begining but ONLY read up to the payload size. We reuse this buffer and it's large //so if we don't specify the length we could end up with an issue. //We have to read for and additional two bytes due to the payyload data shifted 2 bytes forward payload = Serializer.Deserialize <TReadPayloadBaseType>(PacketPayloadReadBuffer, 0, header.PayloadSize + 2); } return(new NetworkIncomingMessage <TReadPayloadBaseType>(header, payload)); }
private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e) { CoreLog.DebugFormat("[TcpChannel OnReceiveCompleted] socket error is '{0}', bytes transffered is {1}.", e.SocketError, e.BytesTransferred); // Receiving failed. if (e.SocketError != SocketError.Success) { Close(); OnError("Receiving data failed. Error data is a SocketError.", e.SocketError); return; } // Server stops this connection. if (e.BytesTransferred == 0) { Close(); OnError("Server stops this connection.", null); return; } // Receiving succeeded. m_ReceiveStream.Write(m_ReceiveBuffer, 0, e.BytesTransferred); long length = m_ReceiveStream.Position; m_ReceiveStream.Position = 0; while (m_ReceiveStream.Position < length) { if (m_CurrentPacketHeader == null) // Should read the next packet header. { // Packet header has not been completed received. if (length - m_ReceiveStream.Position < ReceivePacketHeaderLength) { break; } // Read the packet header. m_CurrentPacketHeader = Handler.DeserializePacketHeader(m_ReceiveStream); } else // Should read the next packet body. { // Current packet has not been completely received. if (length - m_ReceiveStream.Position < m_CurrentPacketHeader.PacketLength) { break; } { var packetHeader = m_CurrentPacketHeader; m_CurrentPacketHeader = null; var packet = Handler.Deserialize(packetHeader, m_ReceiveStream); lock (m_PacketsToReceive) { m_PacketsToReceive.Enqueue(packet); } } } } var underlyingBuffer = m_ReceiveStream.GetBuffer(); Buffer.BlockCopy(underlyingBuffer, (int)m_ReceiveStream.Position, underlyingBuffer, 0, (int)(length - m_ReceiveStream.Position)); m_ReceiveStream.Position = length - m_ReceiveStream.Position; if (m_State != NetChannelState.Connected) { return; } Receive(); }
public ReceiveState() { m_Stream = new MemoryStream(DefaultBufferLength); m_PacketHeader = null; m_Disposed = false; }