Ejemplo n.º 1
0
        /// <summary>
        /// Receive <see cref="AsyncCallback"/> method.
        /// </summary>
        /// <exception cref="InvalidOperationException" />
        protected override unsafe void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                MReceivedLength += MSocket.EndReceive(ar);

                fixed(byte *buf = MReceiveBuffer)
                {
                    if (!MHeaderReceived) //get packet capacity
                    {
                        L2Buffer.Extend(ref MReceiveBuffer, 0, *(int *)buf - sizeof(int));
                        MReceivedLength = 0;
                        MHeaderReceived = true;
                    }

                    if (MReceivedLength == MReceiveBuffer.Length) // all data received
                    {
                        Handle(new Packet(2, MReceiveBuffer));

                        MReceivedLength = 0;
                        MReceiveBuffer  = MDefaultBuffer;
                        MHeaderReceived = false;

                        MSocket.BeginReceive(MReceiveBuffer, 0, 4, 0, ReceiveCallback, null);
                    }
                    else
                    {
                        if (MReceivedLength < MReceiveBuffer.Length) // not all data received
                        {
                            MSocket.BeginReceive(MReceiveBuffer, MReceivedLength, MReceiveBuffer.Length - MReceivedLength, 0, MReceiveCallback, null);
                        }
                        else
                        {
                            throw new InvalidOperationException();
                        }
                    }
                }
            }
            catch (SocketException se)
            {
                Log.Info(string.Format("{0} \r\nError code: {1}", se.ToString(), se.ErrorCode));

                CloseConnection();

                OnDisconnected?.Invoke(se.ErrorCode, this, ConnectionId);
            }
            catch (Exception e)
            {
                Log.Error(e);

                CloseConnection();

                OnDisconnected?.Invoke(-1, this, ConnectionId);
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Begins receive from connection socket.
 /// </summary>
 public override void BeginReceive()
 {
     MSocket.BeginReceive(MReceiveBuffer, 0, 4, 0, MReceiveCallback, null);
 }