Example #1
0
        private void OnReceive(IAsyncResult result)
        {
            if (disposed)
            {
                return;
            }

            try
            {
                var bytesRead = handler.EndReceive(result);
                if (bytesRead > 0)
                {
                    OnPackagePartReceived();

                    received.Write(buffer, 0, bytesRead);

                    while (packer.IsPackageReceived(received))
                    {
                        var size = packer.GetPackageSize(received);
                        if (size > MaxReceivedDataSize)
                        {
                            throw new ModelException(ErrorCode.LargeReceivedData);
                        }

                        var unpacked = packer.Unpack <IPackage>(received);

                        var length = (int)received.Length;

                        received.Position = 0;
                        received.SetLength(0);

                        var restDataSize = length - size;
                        if (restDataSize > 0)
                        {
                            var dataBuffer = received.GetBuffer();
                            received.Write(dataBuffer, size, restDataSize);
                        }

                        switch (unpacked.Package.Id)
                        {
                        case RemoteInfoId:
                            if (!connectionInfoSent)
                            {
                                SendInfo();
                            }

                            SetRemoteInfo(unpacked.Package);
                            unpacked.Dispose();
                            break;

                        default:
                            OnPackageReceived(new PackageReceivedEventArgs(unpacked));
                            break;
                        }
                    }
                }

                handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnReceive, null);
            }
            catch (SocketException se)
            {
                if (!OnSocketException(se))
                {
                    OnPackageReceived(new PackageReceivedEventArgs(se));
                }
            }
            catch (Exception e)
            {
                OnPackageReceived(new PackageReceivedEventArgs(e));
            }
        }