Exemplo n.º 1
0
        private void OnReceive(IAsyncResult ar)
        {
            Sock.Server sock = ar.AsyncState as Sock.Server;

            int receivedLength = 0;

            try
            {
                receivedLength = sock.ServerSocket.EndReceive(ar);
            }
            catch (Exception ex)
            {
                if (string.Equals(ex.Message, "Object reference not set to an instance of an object.") |
                    string.Equals(ex.Message, "An existing connection was forcibly closed by the remote host"))
                {
                    if (OnServerDisconnect != null)
                    {
                        OnServerDisconnect();
                    }
                }
            }

            if (receivedLength != 0)
            {
                if (UseEncryption)
                {
                    byte[] dataPacket = new byte[receivedLength];
                    Buffer.BlockCopy(DataBuffer, 0, dataPacket, 0, receivedLength);

                    byte[] decrypted = Decompress(EncryptionSettings.Decrypt(dataPacket, EncryptionKey));

                    if (OnDataReceived != null)
                    {
                        OnDataReceived(sock, DataFormatter.ConvertToObject(decrypted));
                    }

                    sock.ServerSocket.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), sock);
                }
                else
                {
                    byte[] dataPacket = new byte[receivedLength];
                    Buffer.BlockCopy(DataBuffer, 0, dataPacket, 0, receivedLength);

                    if (OnDataReceived != null)
                    {
                        OnDataReceived(sock, DataFormatter.ConvertToObject(Decompress(dataPacket)));
                    }

                    sock.ServerSocket.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), sock);
                }
            }
        }