Esempio n. 1
0
 public void should_throw_an_unabletocreatememoryexception_if_acquiring_memory_is_disabled_and_out_of_memory()
 {
     BufferManager manager = new BufferManager(1, 1000, 1, false);
     manager.CheckOut();
     //should be none left, boom
     Assert.Throws<UnableToCreateMemoryException>(() => manager.CheckOut());
 }
Esempio n. 2
0
        public CrcConnection(Connection connection, BufferManager bufferManager)
        {
            _connection = connection;
            _bufferManager = bufferManager;

            _connect = true;
        }
        public static ArraySegment<byte> AppendPayloadAsHeader(ArraySegment<byte> buffer, ArraySegment<byte> payload, BufferManager bufferManager)
        {
            // We will insert at the beginning of the buffer just before the dictionary or any message content
            int posToInsert = buffer.Offset;
             
            int frameSize = PayloadMarkLength + PayloadLengthByteCount + payload.Count;
 
            byte[] newBuffer = bufferManager.TakeBuffer(buffer.Count + frameSize + buffer.Offset);
 
            int afterContent = posToInsert + frameSize;
 
            // Insert our custom mark 0xBE
            int insertPoint = posToInsert;
            newBuffer[insertPoint++] = PayloadMark;
 
            // Insert the length of the payload
            byte[] lenInBytes = BitConverter.GetBytes(payload.Count);
            newBuffer[insertPoint++] = lenInBytes[0];
            newBuffer[insertPoint++] = lenInBytes[1];
            newBuffer[insertPoint++] = lenInBytes[2];
            newBuffer[insertPoint++] = lenInBytes[3];
 
            Buffer.BlockCopy(payload.Array, payload.Offset, newBuffer, insertPoint, payload.Count);
 
            // Copy from old to new array
            Buffer.BlockCopy(buffer.Array, 0, newBuffer, 0, posToInsert); // Copy until the subheader pointer
            Buffer.BlockCopy(buffer.Array, posToInsert, newBuffer, afterContent, buffer.Count - posToInsert + buffer.Offset); // Now copy the rest
 
            return new ArraySegment<byte>(newBuffer, buffer.Offset, buffer.Count + frameSize);
        }
        public static bool GetAndRemoveHeaderPayload(ref ArraySegment<byte> buffer, BufferManager bufferManager, out OutOfBandPayloadProperty payload)
        {
            int ptrPayload;
            if (DoesBufferContainPayload(buffer, out ptrPayload))
            {
                int endOfPayload;
 
                // Get the payload content
                ArraySegment<byte> payloadSegment = BinaryFormatHelper.GetPayloadSegment(buffer, ptrPayload, out endOfPayload);
                payload = new OutOfBandPayloadProperty(payloadSegment);
 
                // Remove it from the message (In place)
                int totalPayloadSize = endOfPayload - ptrPayload;
                int newBufferSize = buffer.Offset + buffer.Count - totalPayloadSize;
 
                Buffer.BlockCopy(buffer.Array, endOfPayload, buffer.Array, ptrPayload, buffer.Count - endOfPayload);
                 
                // Return the new buffer without the payload
                buffer = new ArraySegment<byte>(buffer.Array, buffer.Offset, buffer.Count - totalPayloadSize);
 
                return true;
            }
 
            payload = null;
            return false;
        }
Esempio n. 5
0
File: Bot.cs Progetto: lythm/orb3d
            public Bot(BotManager manager,BotDescriptor BotDesc, int BotId)
            {
                FBotId = BotId;
                FManager = manager;
                FBotDesc = BotDesc;
                FBufferManager = new BufferManager();
                FBufferManager.Initialize(100, 100);

                FPacketSpliter = new PacketSpliter();

                FPacketSpliter.OnPacket += OnPacket;

                FConnArg = new SocketAsyncEventArgs();
                FConnArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
                FConnArg.UserToken = this;
                FConnArg.RemoteEndPoint = FBotDesc.Host;

                FDisconnArg = new SocketAsyncEventArgs();
                FDisconnArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
                FDisconnArg.UserToken = this;
                FDisconnArg.DisconnectReuseSocket = true;

                FSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                FTimer = new Timer(OnTimer);
            }
Esempio n. 6
0
        public BitmapManager(BufferManager bufferManager)
        {
            _bitmapStream = new BufferStream(bufferManager);
            _bufferManager = bufferManager;

            _cacheBuffer = _bufferManager.TakeBuffer(BitmapManager.SectorSize);
        }
Esempio n. 7
0
        public AmoebaManager(string blocksPath, BufferManager bufferManager)
        {
            _blocksPath = blocksPath;
            _bufferManager = bufferManager;

            _clientManager = new ClientManager(_bufferManager);
            _serverManager = new ServerManager(_bufferManager);
            _cacheManager = new CacheManager(_blocksPath, _bufferManager);
            _connectionsManager = new ConnectionsManager(_clientManager, _serverManager, _cacheManager, _bufferManager);
            _downloadManager = new DownloadManager(_connectionsManager, _cacheManager, _bufferManager);
            _uploadManager = new UploadManager(_connectionsManager, _cacheManager, _bufferManager);
            _backgroundDownloadManager = new BackgroundDownloadManager(_connectionsManager, _cacheManager, _bufferManager);
            _backgroundUploadManager = new BackgroundUploadManager(_connectionsManager, _cacheManager, _bufferManager);

            _clientManager.CreateCapEvent = (object sender, string uri) =>
            {
                return _createCapEvent?.Invoke(this, uri);
            };

            _serverManager.AcceptCapEvent = (object sender, out string uri) =>
            {
                uri = null;
                return _acceptCapEvent?.Invoke(this, out uri);
            };

            _clientManager.CheckUriEvent = (object sender, string uri) =>
            {
                return _checkUriEvent?.Invoke(this, uri) ?? true;
            };

            _serverManager.CheckUriEvent = (object sender, string uri) =>
            {
                return _checkUriEvent?.Invoke(this, uri) ?? true;
            };
        }
Esempio n. 8
0
        public BinaryArray(int length, BufferManager bufferManager)
        {
            _length = length;
            _bufferManager = bufferManager;

            _buffer = _bufferManager.TakeBuffer((_length + (8 - 1)) / 8);
            Unsafe.Zero(_buffer);
        }
Esempio n. 9
0
        public ServerManager(BufferManager bufferManager)
        {
            _bufferManager = bufferManager;

            _settings = new Settings(this.ThisLock);

            _watchTimer = new WatchTimer(this.WatchTimer, Timeout.Infinite);
        }
Esempio n. 10
0
        public BinaryArray(int length, BufferManager bufferManager)
        {
            _length = length;
            _bufferManager = bufferManager;

            _buffer = _bufferManager.TakeBuffer((int)BinaryArray.Roundup(_length, 8));
            Unsafe.Zero(_buffer);
        }
        public CompressConnection(Connection connection, int maxReceiveCount, BufferManager bufferManager)
        {
            _connection = connection;
            _maxReceiveCount = maxReceiveCount;
            _bufferManager = bufferManager;

            _myCompressAlgorithm = CompressAlgorithm.Deflate;
        }
Esempio n. 12
0
 public TcpServerChannel(IPipeline serverPipeline, IPipeline childPipeline, int maxNumberOfClients)
 {
     _bufferManager = new BufferManager(maxNumberOfClients, 65535);
     _argsPool = new ObjectPool<SocketAsyncEventArgs>(AllocateArgs);
     Pipeline = serverPipeline;
     _contexts = new ContextCollection(this);
     ChildPipeline = childPipeline;
 }
Esempio n. 13
0
        public AmoebaManager(string bitmapPath, string cachePath, BufferManager bufferManager)
        {
            _bitmapPath = bitmapPath;
            _cachePath = cachePath;
            _bufferManager = bufferManager;

            _clientManager = new ClientManager(_bufferManager);
            _serverManager = new ServerManager(_bufferManager);
            _bitmapManager = new BitmapManager(_bitmapPath, _bufferManager);
            _cacheManager = new CacheManager(_cachePath, _bitmapManager, _bufferManager);
            _connectionsManager = new ConnectionsManager(_clientManager, _serverManager, _cacheManager, _bufferManager);
            _downloadManager = new DownloadManager(_connectionsManager, _cacheManager, _bufferManager);
            _uploadManager = new UploadManager(_connectionsManager, _cacheManager, _bufferManager);
            _backgroundDownloadManager = new BackgroundDownloadManager(_connectionsManager, _cacheManager, _bufferManager);
            _backgroundUploadManager = new BackgroundUploadManager(_connectionsManager, _cacheManager, _bufferManager);

            _clientManager.CreateCapEvent = (object sender, string uri) =>
            {
                if (_createCapEvent != null)
                {
                    return _createCapEvent(this, uri);
                }

                return null;
            };

            _serverManager.AcceptCapEvent = (object sender, out string uri) =>
            {
                uri = null;

                if (_acceptCapEvent != null)
                {
                    return _acceptCapEvent(this, out uri);
                }

                return null;
            };

            _clientManager.CheckUriEvent = (object sender, string uri) =>
            {
                if (_checkUriEvent != null)
                {
                    return _checkUriEvent(this, uri);
                }

                return true;
            };

            _serverManager.CheckUriEvent = (object sender, string uri) =>
            {
                if (_checkUriEvent != null)
                {
                    return _checkUriEvent(this, uri);
                }

                return true;
            };
        }
Esempio n. 14
0
        public SecureConnection(SecureConnectionVersion version, SecureConnectionType type, Connection connection, DigitalSignature digitalSignature, BufferManager bufferManager)
        {
            _type = type;
            _connection = connection;
            _digitalSignature = digitalSignature;
            _bufferManager = bufferManager;

            _myVersion = version;
        }
 public void GettingADifferentSizeThenConfigured()
 {
     var settings = CreateSettings(1, 10, 1);
     var manager = new BufferManager(settings);
     byte[] test = manager.GetBuffer(11);
     Assert.NotNull(test);
     test = manager.GetBuffer(10);
     Assert.NotNull(test);
 }
 public void GettingMoreThanInitiallyAllocatedWorks()
 {
     var settings = CreateSettings(1, 10, 1);
     var manager = new BufferManager(settings);
     byte[] test = manager.GetBuffer(10);
     Assert.NotNull(test);
     test = manager.GetBuffer(10);
     Assert.NotNull(test);
 }
 public CacheManagerStreamWriter(out KeyCollection keys, int blockLength, HashAlgorithm hashAlgorithm, CacheManager cacheManager, BufferManager bufferManager)
 {
     keys = _keyList;
     _hashAlgorithm = hashAlgorithm;
     _cacheManager = cacheManager;
     _bufferManager = bufferManager;
     _blockBuffer = bufferManager.TakeBuffer(blockLength);
     _blockBufferLength = blockLength;
 }
        public BackgroundUploadManager(ConnectionsManager connectionsManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _connectionsManager = connectionsManager;
            _cacheManager = cacheManager;
            _bufferManager = bufferManager;

            _settings = new Settings();

            _watchTimer = new WatchTimer(this.WatchTimer, Timeout.Infinite);
        }
Esempio n. 19
0
        public TCPServer(TCPServerSettings settings)
        {
            _settings = settings;

            _clients = new ClientToken[_settings.MaxConnections];
            _bufferManager = new BufferManager(_settings.BufferSize, _settings.MaxConnections*2);
            _poolOfDataEventArgs = new Pool<ClientToken>(_settings.MaxConnections, false);
            _poolOfAcceptEventArgs = new Pool<SocketAsyncEventArgs>(_settings.MaxAcceptOps, false);
            _maxConnectionsEnforcer = new Semaphore(_settings.MaxConnections, _settings.MaxConnections);
        }
Esempio n. 20
0
        public ReedSolomon8(int k, int n, int threadCount, BufferManager bufferManager)
        {
            _fecMath = new Math();
            _k = k;
            _n = n;
            _threadCount = threadCount;
            _bufferManager = bufferManager;

            _encMatrix = _fecMath.CreateEncodeMatrix(k, n);
        }
        public CacheManager_StreamReader(KeyCollection keys, CacheManager cacheManager, BufferManager bufferManager)
        {
            _cacheManager = cacheManager;
            _keys = keys;
            _bufferManager = bufferManager;

            _blockBuffer = _cacheManager[_keys[_keysIndex]];
            _keysIndex++;

            _length = keys.Sum(n => (long)cacheManager.GetLength(n));
        }
Esempio n. 22
0
 public QueueStream(Stream stream, StreamMode mode, int bufferSize, BufferManager bufferManager)
 {
     if (mode == StreamMode.Read)
     {
         _stream = new ReadStream(stream, bufferSize, bufferManager);
     }
     else if (mode == StreamMode.Write)
     {
         _stream = new WriteStream(new CacheStream(stream, QueueStream.BlockSize, bufferManager), bufferSize, bufferManager);
     }
 }
Esempio n. 23
0
        public MeshManager(BufferManager bufferManager)
        {
            BufferManager = bufferManager;

            // Each empty handle will store the location of the next empty handle
            for (var i = 0; i < Handles.Length; i++)
            {
                Handles[i].Id = (short)(i + 1);
            }

            Handles[Handles.Length - 1].Id = -1;
        }
Esempio n. 24
0
 /// <summary>
 /// Attaches the object to an existing socket.
 /// </summary>
 public TcpServerChannel(
     string                        contextId,
     UaTcpChannelListener          listener,
     BufferManager                 bufferManager, 
     TcpChannelQuotas              quotas,
     X509Certificate2              serverCertificate, 
     EndpointDescriptionCollection endpoints)
 :
     base(contextId, bufferManager, quotas, serverCertificate, endpoints, MessageSecurityMode.None, SecurityPolicies.None)
 {
     m_listener = listener;
     m_queuedResponses = new SortedDictionary<uint,IServiceResponse>();
 }
Esempio n. 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BufferPool"/> class.
 /// </summary>
 /// <param name="initialBufferCount">The number of initial buffers.</param>
 /// <param name="bufferManager">The buffer manager.</param>
 public BufferPool(int initialBufferCount, BufferManager bufferManager)
 {
     if (initialBufferCount <= 0)
         throw new ArgumentException("initialBufferCount");
     if (bufferManager == null)
         throw new ArgumentNullException("bufferManager");
     _length = 0;
     _buffers = new List<ArraySegment<byte>>(bufferManager.CheckOut(initialBufferCount));
     // must have 1 buffer
     _chunkSize = _buffers[0].Count;
     _bufferManager = bufferManager;
     _disposed = false;
 }
Esempio n. 26
0
File: Server.cs Progetto: vls/hp2p
        int m_totalBytesRead; // counter of the total # bytes received by the server

        #endregion Fields

        #region Constructors

        // Create an uninitialized server instance.
        // To start the server listening for connection requests
        // call the Init method followed by Start method
        //
        // <param name="numConnections">the maximum number of connections the sample is designed to handle simultaneously</param>
        // <param name="receiveBufferSize">buffer size to use for each socket I/O operation</param>
        public Server(int numConnections, int receiveBufferSize)
        {
            m_totalBytesRead = 0;
            m_numConnectedSockets = 0;
            m_numConnections = numConnections;
            m_receiveBufferSize = receiveBufferSize;
            // allocate buffers such that the maximum number of sockets can have one outstanding read and
            //write posted to the socket simultaneously
            m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc,
                receiveBufferSize);

            m_readWritePool = new SocketAsyncEventArgsPool(numConnections);
            m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);
        }
        public void CanWeClearBufferContent()
        {
            var settings = CreateSettings(1, 10, 1);
            var manager = new BufferManager(settings);
            byte[] test = manager.GetBuffer(10);
            test[0] = 0x01;
            Assert.NotNull(test);
            Assert.AreEqual(test.Length, 10); //we get the same length

            manager.FreeBuffer(ref test, true);

            test = manager.GetBuffer(10);
            Assert.True(test[0] == 0x00);//we got a cleared one
        }
        public SimpleHttpGetByRangeClient(Uri baseUri, BufferManager bufferManager = null, int timeout = DEFAULT_TIMEOUT, Uri proxy = null)
        {
            this.baseUri = baseUri;

            this.proxy = proxy;
            CreateTcpClient(proxy);

            if (bufferManager == null)
            {
                bufferManager = new BufferManager(new[] { new BufferQueueSetting(BUFFER_SIZE, 1) });
            }
            this.bufferManager = bufferManager;
            this.timeout = timeout;
        }
Esempio n. 29
0
        public UploadManager(ConnectionsManager connectionsManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _connectionsManager = connectionsManager;
            _cacheManager = cacheManager;
            _bufferManager = bufferManager;

            _settings = new Settings();

            _threadCount = Math.Max(1, Math.Min(System.Environment.ProcessorCount, 32) / 2);

            _watchTimer = new WatchTimer(this.WatchTimer, Timeout.Infinite);

            _cacheManager.ShareRemoveEvents += this.ShareRemoveThread;
        }
Esempio n. 30
0
        public BaseConnection(Cap cap, BandwidthLimit bandwidthLimit, int maxReceiveCount, BufferManager bufferManager)
        {
            _cap = cap;
            _bandwidthLimit = bandwidthLimit;
            _maxReceiveCount = maxReceiveCount;
            _bufferManager = bufferManager;

            if (_bandwidthLimit != null) _bandwidthLimit.Join(this);

            _aliveTimer = new System.Threading.Timer(this.AliveTimer, null, 1000 * 30, 1000 * 30);
            _aliveStopwatch.Start();

            _connect = true;
        }
Esempio n. 31
0
        public void Write(BinaryWriter bw)
        {
            var sizePosition = bw.BaseStream.Position;

            bw.Write((ushort)0);  // Size placeholder

            bw.Write(Channel);
            bw.Write((byte)0);  // padding

            if (Channel != 0)
            {
                bw.Write(SequenceNumber); // sequence num?
                bw.Write(0xDEADBEEF);     // const
                bw.Write(0);              // padding
            }

            var packetBeginPosition = (int)bw.BaseStream.Position;

            var packetBuffer = BufferManager.RequestBuffer();
            int uncompressedSize;

            using (var ms = new MemoryStream(packetBuffer.Buffer, packetBuffer.BaseOffset, packetBuffer.MaxLength, true))
            {
                using (var packetWriter = new BinaryWriter(ms, Encoding.UTF8, true))
                {
                    using (var writer = new ProtocolBufferWriter(packetWriter, ProtocolBufferFlags.DontFragment))
                    {
                        writer.WriteProtocolFlags();

                        writer.WriteDebugByte(41);

                        if ((Message.SubtypeFlags & ClientMessageSubtypeFlag.HasSubtype) == ClientMessageSubtypeFlag.HasSubtype)
                        {
                            writer.WriteByte(Message.RawSubtype);
                        }

                        Message.Write(writer);

                        writer.WriteDebugByte(42);

                        var currentPos = (int)ms.Position;

                        writer.WriteXORCheck(currentPos);

                        uncompressedSize = (int)ms.Position;
                    }
                }
            }

            var compress = (Message.SubtypeFlags & ClientMessageSubtypeFlag.Compress) == ClientMessageSubtypeFlag.Compress && uncompressedSize > 0;

            using (var writer = new ProtocolBufferWriter(bw, ProtocolBufferFlags.DontFragment))
            {
                writer.WriteProtocolFlags();

                writer.WritePacketType((ushort)Message.Type, compress);

                writer.WriteXORCheck((int)bw.BaseStream.Position - packetBeginPosition);
            }

            int packetSize = uncompressedSize;

            if (compress) // TODO: test
            {
                bw.Write((byte)0x01);
                bw.Write(uncompressedSize);

                var compressedBuffer = BufferManager.RequestBuffer();
                int compressedSize;

                using (var compressStream = compressedBuffer.GetStream(true))
                {
                    using (var compressorStream = new DeflateStream(compressStream, CompressionMode.Compress, true))
                        compressorStream.Write(packetBuffer.Buffer, packetBuffer.BaseOffset, uncompressedSize);

                    compressedSize = (int)compressStream.Position;
                }

                BufferManager.FreeBuffer(packetBuffer);

                packetBuffer = compressedBuffer;
                packetSize   = compressedSize;
            }

            bw.Write(packetBuffer.Buffer, packetBuffer.BaseOffset, packetSize);

            BufferManager.FreeBuffer(packetBuffer);

            var currentPosition = bw.BaseStream.Position;

            bw.BaseStream.Position = sizePosition;

            bw.Write((ushort)(currentPosition - sizePosition));

            bw.BaseStream.Position = currentPosition;
        }
Esempio n. 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProtoBufMessageFormatter{T}"/> class.
 /// </summary>
 /// <param name="bufferManager">The buffer manager.</param>
 public ProtoBufMessageFormatter(BufferManager bufferManager) : this(bufferManager, 2)
 {
 }
Esempio n. 33
0
        public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriter    writer = XmlWriter.Create(stream, _writerSettings);

            message.WriteMessage(writer);
            writer.Close();

            byte[] messageBytes  = stream.GetBuffer();
            int    messageLength = (int)stream.Position;

            stream.Close();

            int totalLength = messageLength + messageOffset;

            byte[] totalBytes = bufferManager.TakeBuffer(totalLength);
            Array.Copy(messageBytes, 0, totalBytes, messageOffset, messageLength);

            ArraySegment <byte> byteArray = new ArraySegment <byte>(totalBytes, messageOffset, messageLength);

            return(byteArray);
        }
Esempio n. 34
0
 public DependencyInjectionFixture() : base()
 {
     BufferManager = new BufferManager();
     BufferManager.InitBuffer(200, 100);
 }
Esempio n. 35
0
        public static IObservable <DisposableBuffer> ToFrameClientObservable(this Socket socket, SocketFlags socketFlags, BufferManager bufferManager)
        {
            return(Observable.Create <DisposableBuffer>(async(observer, token) =>
            {
                var headerBuffer = new byte[sizeof(int)];

                try
                {
                    while (!token.IsCancellationRequested)
                    {
                        if (await socket.ReceiveCompletelyAsync(headerBuffer, headerBuffer.Length, socketFlags, token) != headerBuffer.Length)
                        {
                            break;
                        }
                        var length = BitConverter.ToInt32(headerBuffer, 0);

                        var buffer = bufferManager.TakeBuffer(length);
                        if (await socket.ReceiveCompletelyAsync(buffer, length, socketFlags, token) != length)
                        {
                            break;
                        }

                        observer.OnNext(new DisposableBuffer(buffer, length, Disposable.Create(() => bufferManager.ReturnBuffer(buffer))));
                    }

                    observer.OnCompleted();

                    socket.Close();
                }
                catch (Exception error)
                {
                    observer.OnError(error);
                }
            }));
        }
 public override Message ReadMessage(ArraySegment <byte> buffer, BufferManager bufferManager, string contentType)
 {
     return(this.mtom.ReadMessage(buffer, bufferManager, contentType));
 }
Esempio n. 37
0
        public void should_throw_argumentnullexception_if_null_buffer()
        {
            BufferManager manager = new BufferManager(10, 1000, 0);

            Assert.Throws <ArgumentNullException>(() => { manager.CheckIn(null); });
        }
Esempio n. 38
0
        /// <summary>
        /// Performs a buffer to buffer, or buffer to texture copy.
        /// </summary>
        /// <param name="state">Current GPU state</param>
        /// <param name="argument">Method call argument</param>
        private void CopyBuffer(GpuState state, int argument)
        {
            var cbp = state.Get <CopyBufferParams>(MethodOffset.CopyBufferParams);

            var swizzle = state.Get <CopyBufferSwizzle>(MethodOffset.CopyBufferSwizzle);

            bool srcLinear = (argument & (1 << 7)) != 0;
            bool dstLinear = (argument & (1 << 8)) != 0;
            bool copy2D    = (argument & (1 << 9)) != 0;

            int size = cbp.XCount;

            if (size == 0)
            {
                return;
            }

            if (copy2D)
            {
                // Buffer to texture copy.
                int srcBpp = swizzle.UnpackSrcComponentsCount() * swizzle.UnpackComponentSize();
                int dstBpp = swizzle.UnpackDstComponentsCount() * swizzle.UnpackComponentSize();

                var dst = state.Get <CopyBufferTexture>(MethodOffset.CopyBufferDstTexture);
                var src = state.Get <CopyBufferTexture>(MethodOffset.CopyBufferSrcTexture);

                var srcCalculator = new OffsetCalculator(
                    src.Width,
                    src.Height,
                    cbp.SrcStride,
                    srcLinear,
                    src.MemoryLayout.UnpackGobBlocksInY(),
                    srcBpp);

                var dstCalculator = new OffsetCalculator(
                    dst.Width,
                    dst.Height,
                    cbp.DstStride,
                    dstLinear,
                    dst.MemoryLayout.UnpackGobBlocksInY(),
                    dstBpp);

                ulong srcBaseAddress = _context.MemoryManager.Translate(cbp.SrcAddress.Pack());
                ulong dstBaseAddress = _context.MemoryManager.Translate(cbp.DstAddress.Pack());

                for (int y = 0; y < cbp.YCount; y++)
                {
                    for (int x = 0; x < cbp.XCount; x++)
                    {
                        int srcOffset = srcCalculator.GetOffset(src.RegionX + x, src.RegionY + y);
                        int dstOffset = dstCalculator.GetOffset(dst.RegionX + x, dst.RegionY + y);

                        ulong srcAddress = srcBaseAddress + (ulong)srcOffset;
                        ulong dstAddress = dstBaseAddress + (ulong)dstOffset;

                        ReadOnlySpan <byte> pixel = _context.PhysicalMemory.GetSpan(srcAddress, srcBpp);

                        _context.PhysicalMemory.Write(dstAddress, pixel);
                    }
                }
            }
            else
            {
                // Buffer to buffer copy.
                BufferManager.CopyBuffer(cbp.SrcAddress, cbp.DstAddress, (uint)size);
            }
        }
Esempio n. 39
0
 protected Class1(Socket socket, BufferManager bufferManager, IPEndPoint endPoint)
 {
     _socket       = socket;
     BufferManager = bufferManager;
     EndPoint      = endPoint;
 }
Esempio n. 40
0
        public void Download()
        {
            if (parameters.OverWrite)
            {
                DeleteTempVhdIfExist(parameters.LocalFilePath);
            }
            else
            {
                if (File.Exists(parameters.LocalFilePath))
                {
                    var message = String.Format("File already exists, you can use Overwrite option to delete it:'{0}'", parameters.LocalFilePath);
                    throw new ArgumentException(message);
                }
            }

            var blobHandle = new BlobHandle(parameters.BlobUri, this.parameters.StorageAccountKey);

            if (parameters.ValidateFreeDiskSpace)
            {
                TryValidateFreeDiskSpace(parameters.LocalFilePath, blobHandle.Length);
            }

            const int megaByte = 1024 * 1024;

            var ranges         = blobHandle.GetUploadableRanges();
            var bufferManager  = BufferManager.CreateBufferManager(Int32.MaxValue, 20 * megaByte);
            var downloadStatus = new ProgressStatus(0, ranges.Sum(r => r.Length), new ComputeStats());

            Trace.WriteLine(String.Format("Total Data:{0}", ranges.Sum(r => r.Length)));

            Program.SyncOutput.WriteVerboseWithTimestamp("Downloading the blob: {0}", parameters.BlobUri.BlobName);

            using (new ServicePointHandler(parameters.BlobUri.Uri, parameters.ConnectionLimit))
            {
                using (new ProgressTracker(downloadStatus, parameters.ProgressDownloadStatus, parameters.ProgressDownloadComplete, TimeSpan.FromSeconds(1)))
                {
                    using (var fileStream = new FileStream(parameters.LocalFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 8 * megaByte, FileOptions.WriteThrough))
                    {
                        fileStream.SetLength(0);
                        fileStream.SetLength(blobHandle.Length);

                        LoopResult lr = Parallel.ForEach <IndexRange, Stream>(ranges,
                                                                              blobHandle.OpenStream,
                                                                              (r, b) =>
                        {
                            b.Seek(r.StartIndex, SeekOrigin.Begin);

                            byte[] buffer = this.EnsureReadAsSize(b, (int)r.Length, bufferManager);

                            lock (fileStream)
                            {
                                Trace.WriteLine(String.Format("Range:{0}", r));
                                fileStream.Seek(r.StartIndex, SeekOrigin.Begin);
                                fileStream.Write(buffer, 0, (int)r.Length);
                                fileStream.Flush();
                            }

                            downloadStatus.AddToProcessedBytes((int)r.Length);
                        },
                                                                              pbwlf =>
                        {
                            pbwlf.Dispose();
                        },
                                                                              parameters.ConnectionLimit);

                        if (lr.IsExceptional)
                        {
                            throw new AggregateException(lr.Exceptions);
                        }
                    }
                }
            }
            Program.SyncOutput.WriteVerboseWithTimestamp("Blob downloaded successfullty: {0}", parameters.BlobUri.BlobName);
        }
            public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                if (message == null)
                {
                    throw Error.ArgumentNull("message");
                }

                if (bufferManager == null)
                {
                    throw Error.ArgumentNull("bufferManager");
                }

                if (maxMessageSize < 0)
                {
                    throw Error.ArgumentOutOfRange("maxMessageSize", maxMessageSize, SRResources.NonnegativeNumberRequired);
                }

                if (messageOffset < 0)
                {
                    throw Error.ArgumentOutOfRange("messageOffset", messageOffset, SRResources.NonnegativeNumberRequired);
                }

                if (messageOffset > maxMessageSize)
                {
                    throw Error.Argument(String.Empty, SRResources.ParameterMustBeLessThanOrEqualSecondParameter, "messageOffset", "maxMessageSize");
                }

                // TODO: DevDiv2 bug #378887 -- find out how to eliminate this middle buffer
                using (BufferManagerOutputStream stream = new BufferManagerOutputStream(MaxSentMessageSizeExceededResourceStringName, 0, maxMessageSize, bufferManager))
                {
                    int num;
                    stream.Skip(messageOffset);
                    WriteMessage(message, stream);

                    byte[] buffer = stream.ToArray(out num);
                    ArraySegment <byte> messageData = new ArraySegment <byte>(buffer, 0, num - messageOffset);

                    // ToArray transfers full ownership of buffer to us, meaning we are responsible for returning it to BufferManager.
                    // But we must delay that release until WCF has finished with the buffer we are returning from this method.
                    HttpMessageEncodingRequestContext requestContext = HttpMessageEncodingRequestContext.GetContextFromMessage(message);
                    Contract.Assert(requestContext != null);
                    requestContext.BufferManager  = bufferManager;
                    requestContext.BufferToReturn = buffer;

                    return(messageData);
                }
            }
Esempio n. 42
0
        public void Read(BinaryReader br)
        {
            if (br.BaseStream.Length < 4)
            {
                throw new Exception("Fragmented receive, should not happen! (4 size header)");
            }

            Size    = br.ReadUInt16();
            Channel = br.ReadByte();

            br.ReadByte(); // padding

            if (Size > br.BaseStream.Length)
            {
                throw new Exception("Fragmented receive, should not happen!");
            }

            if (Channel == 0xFF) // Internal channel: Send timeout checking, ignore the packet
            {
                return;
            }

            if (Channel != 0) // 0 == ReliableStreamChannel (no extra data), Move message uses channels
            {
                Debugger.Break();

                SequenceNumber = br.ReadUInt32(); // Sequence number? if (previousValue - newValue < 0) { process packet; previousValue = newValue; }
                br.ReadInt32();                   // 0xDEADBEEF
                br.ReadInt32();                   // skip
            }

            var packetBeginPosition = br.BaseStream.Position;

            using (var reader = new ProtocolBufferReader(br, ProtocolBufferFlags.DontFragment))
            {
                reader.ReadProtocolFlags();

                ushort type;
                bool   compress;

                reader.ReadPacketType(out type, out compress);

                Type     = (ClientMessageOpcode)type;
                Compress = compress;

                reader.ReadXORCheck((int)(br.BaseStream.Position - packetBeginPosition));
            }

            var xorCheckPosition = (int)br.BaseStream.Position;

            var readBr = br;

            BufferData buffer = null;

            if (Compress)
            {
                var someType = br.ReadByte(); // 0 = No compression
                if (someType >= 2)
                {
                    throw new Exception("Invalid compress type received!");
                }

                if (someType == 1)
                {
                    Debugger.Break(); // TODO: test

                    var uncompressedSize = br.ReadInt32();

                    byte[] uncompressedData;
                    var    offset = 0;

                    if (uncompressedSize > BufferManager.BlockSize)
                    {
                        uncompressedData = new byte[uncompressedSize];
                    }
                    else
                    {
                        buffer = BufferManager.RequestBuffer();

                        uncompressedData = buffer.Buffer;
                        offset           = buffer.BaseOffset;
                    }

                    using (var deflateStream = new DeflateStream(br.BaseStream, CompressionMode.Decompress, true)) // TODO: test if the br.BaseStream is cool as the Stream input for the DeflateStream
                        deflateStream.Read(uncompressedData, offset, uncompressedSize);

                    readBr = buffer != null?buffer.GetReader() : new BinaryReader(new MemoryStream(uncompressedData, 0, uncompressedSize, false), Encoding.UTF8, false);
                }
            }

            // ReSharper disable SwitchStatementMissingSomeCases
            switch (Type)
            {
            case ClientMessageOpcode.Login:
                Message = new LoginMessage();
                break;

            case ClientMessageOpcode.Move:
                Message = new MoveMessage();
                break;

            case ClientMessageOpcode.CallServerMethod:
                Message = new CallServerMethodMessage();
                break;

            case ClientMessageOpcode.Ping:
                Message = new PingMessage();
                break;

            default:
                throw new Exception($"Unable to handle packet type {Type}, because it's a Server -> Client packet!");
            }
            // ReSharper restore SwitchStatementMissingSomeCases

            using (var reader = new ProtocolBufferReader(readBr, ProtocolBufferFlags.DontFragment))
            {
                reader.ReadProtocolFlags();

                // Subtype and Message.Read()
                reader.ReadDebugByte(41);

                if ((Message.SubtypeFlags & ClientMessageSubtypeFlag.HasSubtype) == ClientMessageSubtypeFlag.HasSubtype)
                {
                    Message.RawSubtype = reader.ReadByte();
                    if (Message.RawSubtype < Message.MinSubtype || Message.RawSubtype > Message.MaxSubtype)
                    {
                        throw new Exception("Invalid Subtype found!");
                    }
                }

                Message.Read(reader);

                reader.ReadDebugByte(42);

                reader.ReadXORCheck((int)br.BaseStream.Position - xorCheckPosition);
            }

            if (buffer != null) // If we requested a buffer for decompressing, free it
            {
                BufferManager.FreeBuffer(buffer);
            }
        }
Esempio n. 43
0
        /// <summary>
        /// Updates host shaders based on the guest GPU state.
        /// </summary>
        /// <param name="state">Current GPU state</param>
        private void UpdateShaderState(GpuState state)
        {
            ShaderAddresses addresses = new ShaderAddresses();

            Span <ShaderAddresses> addressesSpan = MemoryMarshal.CreateSpan(ref addresses, 1);

            Span <ulong> addressesArray = MemoryMarshal.Cast <ShaderAddresses, ulong>(addressesSpan);

            ulong baseAddress = state.Get <GpuVa>(MethodOffset.ShaderBaseAddress).Pack();

            for (int index = 0; index < 6; index++)
            {
                var shader = state.Get <ShaderState>(MethodOffset.ShaderState, index);

                if (!shader.UnpackEnable() && index != 1)
                {
                    continue;
                }

                addressesArray[index] = baseAddress + shader.Offset;
            }

            ShaderBundle gs = ShaderCache.GetGraphicsShader(state, addresses);

            _vsUsesInstanceId = gs.Shaders[0]?.Program.Info.UsesInstanceId ?? false;

            int storageBufferBindingsCount = 0;
            int uniformBufferBindingsCount = 0;

            for (int stage = 0; stage < Constants.ShaderStages; stage++)
            {
                ShaderProgramInfo info = gs.Shaders[stage]?.Program.Info;

                _currentProgramInfo[stage] = info;

                if (info == null)
                {
                    TextureManager.SetGraphicsTextures(stage, Array.Empty <TextureBindingInfo>());
                    TextureManager.SetGraphicsImages(stage, Array.Empty <TextureBindingInfo>());
                    BufferManager.SetGraphicsStorageBufferBindings(stage, null);
                    BufferManager.SetGraphicsUniformBufferBindings(stage, null);
                    continue;
                }

                var textureBindings = new TextureBindingInfo[info.Textures.Count];

                for (int index = 0; index < info.Textures.Count; index++)
                {
                    var descriptor = info.Textures[index];

                    Target target = ShaderTexture.GetTarget(descriptor.Type);

                    textureBindings[index] = new TextureBindingInfo(
                        target,
                        descriptor.Binding,
                        descriptor.CbufSlot,
                        descriptor.HandleIndex,
                        descriptor.Flags);
                }

                TextureManager.SetGraphicsTextures(stage, textureBindings);

                var imageBindings = new TextureBindingInfo[info.Images.Count];

                for (int index = 0; index < info.Images.Count; index++)
                {
                    var descriptor = info.Images[index];

                    Target target = ShaderTexture.GetTarget(descriptor.Type);
                    Format format = ShaderTexture.GetFormat(descriptor.Format);

                    imageBindings[index] = new TextureBindingInfo(
                        target,
                        format,
                        descriptor.Binding,
                        descriptor.CbufSlot,
                        descriptor.HandleIndex,
                        descriptor.Flags);
                }

                TextureManager.SetGraphicsImages(stage, imageBindings);

                BufferManager.SetGraphicsStorageBufferBindings(stage, info.SBuffers);
                BufferManager.SetGraphicsUniformBufferBindings(stage, info.CBuffers);

                if (info.SBuffers.Count != 0)
                {
                    storageBufferBindingsCount = Math.Max(storageBufferBindingsCount, info.SBuffers.Max(x => x.Binding) + 1);
                }

                if (info.CBuffers.Count != 0)
                {
                    uniformBufferBindingsCount = Math.Max(uniformBufferBindingsCount, info.CBuffers.Max(x => x.Binding) + 1);
                }
            }

            BufferManager.SetGraphicsStorageBufferBindingsCount(storageBufferBindingsCount);
            BufferManager.SetGraphicsUniformBufferBindingsCount(uniformBufferBindingsCount);

            _context.Renderer.Pipeline.SetProgram(gs.HostProgram);
        }
        private void Init()
        {
            if (!isInit)
            {
                lock (lockForPickObject)
                {
                    if (!isInit)
                    {
                        Stopwatch sw = new Stopwatch();

                        sw.Start();

                        clientSetting = GetLocalClientSetting();

                        ServerCount = clientSetting.serverEndPoints.Length;

                        timeOutByMS = clientSetting.timeOutByMS;

                        //初始化后,不可更改!
                        bufferManager = new BufferManager(clientSetting.bufferSize * clientSetting.opsToPreAllocate * clientSetting.numberOfSaeaForRecSend, clientSetting.bufferSize * clientSetting.opsToPreAllocate);
                        bufferManager.InitBuffer();

                        //用于负责建立连接的saea,无关buffermanager,10个足够!这部分实际在ClientSocketProcessor中可以动态增加
                        //poolOfConnectEventArgs = new SocketAsyncEventArgPool(clientSetting.maxSimultaneousConnectOps);
                        poolOfConnectEventArgs = new SocketAsyncEventArgPool();

                        //用于负责在建立好的连接上传输数据,涉及buffermanager,目前测试100~200个足够!这部分目前不支持动态增加!
                        //因其buffermanager是事先分配好的一大块连续的固定内存区域,强烈建议不再更改,需要做好的就是事先的大小评估。
                        //poolOfRecSendEventArgs = new SocketAsyncEventArgPool(clientSetting.numberOfSaeaForRecSend);
                        poolOfRecSendEventArgs = new SocketAsyncEventArgPool();

                        //实际负责处理相关传输数据的关键核心类
                        processor = new ClientSocketProcessor(poolOfConnectEventArgs, poolOfRecSendEventArgs, clientSetting.numberOfSaeaForRecSend, clientSetting.bufferSize, clientSetting.numberOfMessagesPerConnection, clientSetting.receivePrefixLength, clientSetting.useKeepAlive, "bizclient");

                        //由于不涉及buffermanager,可动态增长
                        for (int i = 0; i < clientSetting.maxSimultaneousConnectOps; i++)
                        {
                            SocketAsyncEventArgs connectEventArg = new SocketAsyncEventArgs();
                            connectEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(processor.IO_Completed);

                            //关键负责标识saea和更关键的传输待发送的数据给传输用的saea。
                            ConnectOpUserToken theConnectingToken = new ConnectOpUserToken();
                            connectEventArg.UserToken = theConnectingToken;

                            poolOfConnectEventArgs.Push(connectEventArg);
                        }

                        //涉及buffermanager,不可动态增长,需事先评估即可,负责实际的数据传输
                        for (int i = 0; i < clientSetting.numberOfSaeaForRecSend; i++)
                        {
                            SocketAsyncEventArgs eventArgObjectForPool = new SocketAsyncEventArgs();

                            //事先为每个saea分配固定不变的内存位置!
                            bufferManager.SetBuffer(eventArgObjectForPool);

                            eventArgObjectForPool.Completed += new EventHandler <SocketAsyncEventArgs>(processor.IO_Completed);

                            ClientUserToken receiveSendToken = new ClientUserToken(eventArgObjectForPool.Offset, eventArgObjectForPool.Offset + clientSetting.bufferSize, clientSetting.receivePrefixLength, clientSetting.sendPrefixLength);

                            //用于传递待发送的数据,一旦完成发送必须重新new一个。
                            receiveSendToken.CreateNewSendDataHolder();
                            eventArgObjectForPool.UserToken = receiveSendToken;

                            poolOfRecSendEventArgs.Push(eventArgObjectForPool);
                        }

                        bufferManager.SetInitComplete();

                        sw.Stop();

                        LogManager.Log(string.Format("SocketClient Init by FirstInvoke Completed! ConsumeTime:{0} ms", sw.ElapsedMilliseconds));

                        isInit = true;
                    }
                }
            }
        }
 public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
 {
     return(this.text.WriteMessage(message, maxMessageSize, bufferManager, messageOffset));
 }
 /// <summary>
 /// Receive the next block of data from the socket.
 /// </summary>
 private void BeginReceive()
 {
     BufferManager.LockBuffer(_receiveBuffer);
     _receiveTask = _socket.ReceiveAsync(new ArraySegment <byte>(_receiveBuffer),
                                         _open.Token).ContinueWith(EndReceive);
 }
Esempio n. 47
0
 public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager)
 {
     this.Write(buffer, offset, size, immediate, timeout);
     bufferManager.ReturnBuffer(buffer);
 }
Esempio n. 48
0
        public void should_accept_a_checked_out_buffer()
        {
            BufferManager manager = new BufferManager(10, 1000, 0);

            manager.CheckIn(manager.CheckOut());
        }
Esempio n. 49
0
 public static ISubject <DisposableBuffer, DisposableBuffer> ToFrameClientSubject(this Socket socket, SocketFlags socketFlags, BufferManager bufferManager, CancellationToken token)
 {
     return(Subject.Create(socket.ToFrameClientObserver(socketFlags, token), socket.ToFrameClientObservable(socketFlags, bufferManager)));
 }
Esempio n. 50
0
 public FakeClient(int id)
 {
     Id = id;
     m_bufferSegment = BufferManager.GetSegment(ClientManager.BufferSize);
 }
Esempio n. 51
0
 internal ArrayBuffer(BufferManager manager, int bufferSize)
 {
     this.m_manager = manager;
     this.m_array   = new byte[bufferSize];
 }
Esempio n. 52
0
        /// <summary>
        /// Updates host shaders based on the guest GPU state.
        /// </summary>
        /// <param name="state">Current GPU state</param>
        private void UpdateShaderState(GpuState state)
        {
            ShaderAddresses addresses = new ShaderAddresses();

            Span <ShaderAddresses> addressesSpan = MemoryMarshal.CreateSpan(ref addresses, 1);

            Span <ulong> addressesArray = MemoryMarshal.Cast <ShaderAddresses, ulong>(addressesSpan);

            ulong baseAddress = state.Get <GpuVa>(MethodOffset.ShaderBaseAddress).Pack();

            for (int index = 0; index < 6; index++)
            {
                var shader = state.Get <ShaderState>(MethodOffset.ShaderState, index);

                if (!shader.UnpackEnable() && index != 1)
                {
                    continue;
                }

                addressesArray[index] = baseAddress + shader.Offset;
            }

            GraphicsShader gs = ShaderCache.GetGraphicsShader(state, addresses);

            _vsUsesInstanceId = gs.Shaders[0]?.Program.Info.UsesInstanceId ?? false;

            for (int stage = 0; stage < Constants.ShaderStages; stage++)
            {
                ShaderProgramInfo info = gs.Shaders[stage]?.Program.Info;

                _currentProgramInfo[stage] = info;

                if (info == null)
                {
                    continue;
                }

                var textureBindings = new TextureBindingInfo[info.Textures.Count];

                for (int index = 0; index < info.Textures.Count; index++)
                {
                    var descriptor = info.Textures[index];

                    Target target = GetTarget(descriptor.Type);

                    if (descriptor.IsBindless)
                    {
                        textureBindings[index] = new TextureBindingInfo(target, descriptor.CbufSlot, descriptor.CbufOffset);
                    }
                    else
                    {
                        textureBindings[index] = new TextureBindingInfo(target, descriptor.HandleIndex);
                    }
                }

                TextureManager.SetGraphicsTextures(stage, textureBindings);

                var imageBindings = new TextureBindingInfo[info.Images.Count];

                for (int index = 0; index < info.Images.Count; index++)
                {
                    var descriptor = info.Images[index];

                    Target target = GetTarget(descriptor.Type);

                    imageBindings[index] = new TextureBindingInfo(target, descriptor.HandleIndex);
                }

                TextureManager.SetGraphicsImages(stage, imageBindings);

                uint sbEnableMask = 0;
                uint ubEnableMask = 0;

                for (int index = 0; index < info.SBuffers.Count; index++)
                {
                    sbEnableMask |= 1u << info.SBuffers[index].Slot;
                }

                for (int index = 0; index < info.CBuffers.Count; index++)
                {
                    ubEnableMask |= 1u << info.CBuffers[index].Slot;
                }

                BufferManager.SetGraphicsStorageBufferEnableMask(stage, sbEnableMask);
                BufferManager.SetGraphicsUniformBufferEnableMask(stage, ubEnableMask);
            }

            _context.Renderer.Pipeline.SetProgram(gs.HostProgram);
        }
Esempio n. 53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProtoBufMessageFormatter{T}"/> class.
 /// </summary>
 /// <param name="bufferManager">The buffer manager.</param>
 /// <param name="initialBuffers">The number of initial buffers.</param>
 public ProtoBufMessageFormatter(BufferManager bufferManager, int initialBuffers)
 {
     _bufferManager  = bufferManager;
     _initialBuffers = initialBuffers;
 }
Esempio n. 54
0
        internal static void HandleAddObject(ulong clientId, Stream stream)
        {
            using (PooledBitReader reader = PooledBitReader.Get(stream))
            {
                bool  isPlayerObject  = reader.ReadBool();
                ulong networkId       = reader.ReadUInt64Packed();
                ulong ownerId         = reader.ReadUInt64Packed();
                bool  hasParent       = reader.ReadBool();
                ulong?parentNetworkId = null;

                if (hasParent)
                {
                    parentNetworkId = reader.ReadUInt64Packed();
                }

                ulong prefabHash;
                ulong instanceId;
                bool  softSync;

                if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync)
                {
                    softSync   = false;
                    instanceId = 0;
                    prefabHash = reader.ReadUInt64Packed();
                }
                else
                {
                    softSync = reader.ReadBool();

                    if (softSync)
                    {
                        instanceId = reader.ReadUInt64Packed();
                        prefabHash = 0;
                    }
                    else
                    {
                        prefabHash = reader.ReadUInt64Packed();
                        instanceId = 0;
                    }
                }

                Vector3?   pos = null;
                Quaternion?rot = null;
                if (reader.ReadBool())
                {
                    pos = new Vector3(reader.ReadSinglePacked(), reader.ReadSinglePacked(), reader.ReadSinglePacked());
                    rot = Quaternion.Euler(reader.ReadSinglePacked(), reader.ReadSinglePacked(), reader.ReadSinglePacked());
                }

                bool hasPayload    = reader.ReadBool();
                int  payLoadLength = hasPayload ? reader.ReadInt32Packed() : 0;

                NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot);
                SpawnManager.SpawnNetworkedObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, stream, hasPayload, payLoadLength, true, false);

                Queue <BufferManager.BufferedMessage> bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId);

                // Apply buffered messages
                if (bufferQueue != null)
                {
                    while (bufferQueue.Count > 0)
                    {
                        BufferManager.BufferedMessage message = bufferQueue.Dequeue();

                        NetworkingManager.Singleton.HandleIncomingData(message.sender, message.channelName, new ArraySegment <byte>(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false);

                        BufferManager.RecycleConsumedBufferedMessage(message);
                    }
                }
            }
        }
Esempio n. 55
0
        public static ISubject <DisposableBuffer, DisposableBuffer> ToFrameClientSubject(this IPEndPoint endpoint, SocketFlags socketFlags, BufferManager bufferManager, CancellationToken token)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(endpoint);
            return(socket.ToFrameClientSubject(socketFlags, bufferManager, token));
        }
Esempio n. 56
0
        internal static void HandleConnectionApproved(ulong clientId, Stream stream, float receiveTime)
        {
            using (PooledBitReader reader = PooledBitReader.Get(stream))
            {
                NetworkingManager.Singleton.LocalClientId = reader.ReadUInt64Packed();

                uint sceneIndex = 0;
                Guid sceneSwitchProgressGuid = new Guid();

                if (NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement)
                {
                    sceneIndex = reader.ReadUInt32Packed();
                    sceneSwitchProgressGuid = new Guid(reader.ReadByteArray());
                }

                bool sceneSwitch = NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement && NetworkSceneManager.HasSceneMismatch(sceneIndex);

                float netTime = reader.ReadSinglePacked();
                NetworkingManager.Singleton.UpdateNetworkTime(clientId, netTime, receiveTime, true);

                NetworkingManager.Singleton.ConnectedClients.Add(NetworkingManager.Singleton.LocalClientId, new NetworkedClient()
                {
                    ClientId = NetworkingManager.Singleton.LocalClientId
                });


                void DelayedSpawnAction(Stream continuationStream)
                {
                    using (PooledBitReader continuationReader = PooledBitReader.Get(continuationStream))
                    {
                        if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync)
                        {
                            SpawnManager.DestroySceneObjects();
                        }
                        else
                        {
                            SpawnManager.ClientCollectSoftSyncSceneObjectSweep(null);
                        }

                        uint objectCount = continuationReader.ReadUInt32Packed();
                        for (int i = 0; i < objectCount; i++)
                        {
                            bool  isPlayerObject  = continuationReader.ReadBool();
                            ulong networkId       = continuationReader.ReadUInt64Packed();
                            ulong ownerId         = continuationReader.ReadUInt64Packed();
                            bool  hasParent       = continuationReader.ReadBool();
                            ulong?parentNetworkId = null;

                            if (hasParent)
                            {
                                parentNetworkId = continuationReader.ReadUInt64Packed();
                            }

                            ulong prefabHash;
                            ulong instanceId;
                            bool  softSync;

                            if (!NetworkingManager.Singleton.NetworkConfig.EnableSceneManagement || NetworkingManager.Singleton.NetworkConfig.UsePrefabSync)
                            {
                                softSync   = false;
                                instanceId = 0;
                                prefabHash = continuationReader.ReadUInt64Packed();
                            }
                            else
                            {
                                softSync = continuationReader.ReadBool();

                                if (softSync)
                                {
                                    instanceId = continuationReader.ReadUInt64Packed();
                                    prefabHash = 0;
                                }
                                else
                                {
                                    prefabHash = continuationReader.ReadUInt64Packed();
                                    instanceId = 0;
                                }
                            }

                            Vector3?   pos = null;
                            Quaternion?rot = null;
                            if (continuationReader.ReadBool())
                            {
                                pos = new Vector3(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked());
                                rot = Quaternion.Euler(continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked(), continuationReader.ReadSinglePacked());
                            }

                            NetworkedObject netObject = SpawnManager.CreateLocalNetworkedObject(softSync, instanceId, prefabHash, parentNetworkId, pos, rot);
                            SpawnManager.SpawnNetworkedObjectLocally(netObject, networkId, softSync, isPlayerObject, ownerId, continuationStream, false, 0, true, false);

                            Queue <BufferManager.BufferedMessage> bufferQueue = BufferManager.ConsumeBuffersForNetworkId(networkId);

                            // Apply buffered messages
                            if (bufferQueue != null)
                            {
                                while (bufferQueue.Count > 0)
                                {
                                    BufferManager.BufferedMessage message = bufferQueue.Dequeue();

                                    NetworkingManager.Singleton.HandleIncomingData(message.sender, message.channelName, new ArraySegment <byte>(message.payload.GetBuffer(), (int)message.payload.Position, (int)message.payload.Length), message.receiveTime, false);

                                    BufferManager.RecycleConsumedBufferedMessage(message);
                                }
                            }
                        }


                        // Clean up the diffed scene objects. I.E scene objects that have been destroyed
                        if (SpawnManager.pendingSoftSyncObjects.Count > 0)
                        {
                            List <NetworkedObject> objectsToDestroy = new List <NetworkedObject>();

                            foreach (KeyValuePair <ulong, NetworkedObject> pair in SpawnManager.pendingSoftSyncObjects)
                            {
                                objectsToDestroy.Add(pair.Value);
                            }

                            for (int i = 0; i < objectsToDestroy.Count; i++)
                            {
                                MonoBehaviour.Destroy(objectsToDestroy[i].gameObject);
                            }
                        }

                        NetworkingManager.Singleton.IsConnectedClient = true;

                        NetworkingManager.Singleton.InvokeOnClientConnectedCallback(NetworkingManager.Singleton.LocalClientId);
                    }
                }

                if (sceneSwitch)
                {
                    UnityAction <Scene, Scene> onSceneLoaded = null;

                    Serialization.BitStream continuationStream = new Serialization.BitStream();
                    continuationStream.CopyUnreadFrom(stream);
                    continuationStream.Position = 0;

                    void OnSceneLoadComplete()
                    {
                        SceneManager.activeSceneChanged -= onSceneLoaded;
                        NetworkSceneManager.isSpawnedObjectsPendingInDontDestroyOnLoad = false;
                        DelayedSpawnAction(continuationStream);
                    }

                    onSceneLoaded = (oldScene, newScene) => { OnSceneLoadComplete(); };

                    SceneManager.activeSceneChanged += onSceneLoaded;

                    NetworkSceneManager.OnFirstSceneSwitchSync(sceneIndex, sceneSwitchProgressGuid);
                }
                else
                {
                    DelayedSpawnAction(stream);
                }
            }
        }
Esempio n. 57
0
        [ExpectedException(typeof(XmlException))] // (document is expected)
        public void ReadEmptyBuffer()
        {
            var enc = new TextMessageEncodingBindingElement().CreateMessageEncoderFactory().Encoder;

            enc.ReadMessage(new ArraySegment <byte> (new byte [0]), BufferManager.CreateBufferManager(1000, 1000), "text/xml");
        }
        /// <summary>
        /// Process received buffer
        /// </summary>
        private ServiceResult ProcessReceivedBuffer(int bytesRead)
        {
            // complete operation.
            BufferManager.UnlockBuffer(_receiveBuffer);
            Utils.TraceDebug("Bytes read: {0}", bytesRead);
            if (bytesRead == 0)
            {
                // Remote end has closed the connection
                // free the empty receive buffer.
                if (_receiveBuffer != null)
                {
                    _bufferManager.ReturnBuffer(_receiveBuffer,
                                                nameof(ProcessReceivedBuffer));
                    _receiveBuffer = null;
                }
                return(ServiceResult.Create(StatusCodes.BadConnectionClosed,
                                            "Remote side closed connection"));
            }

            _bytesReceived += bytesRead;
            // check if more data left to read.
            if (_bytesReceived < _bytesToReceive)
            {
                BeginReceive();
                return(ServiceResult.Good);
            }
            // start reading the message body.
            if (_incomingMessageSize < 0)
            {
                _incomingMessageSize = BitConverter.ToInt32(_receiveBuffer, 4);
                if (_incomingMessageSize <= 0 ||
                    _incomingMessageSize > _receiveBufferSize)
                {
                    Utils.Trace($"BadTcpMessageTooLarge: BufferSize={_receiveBufferSize}; " +
                                $"MessageSize={_incomingMessageSize}");
                    return(ServiceResult.Create(StatusCodes.BadTcpMessageTooLarge,
                                                "Messages size {1} bytes is too large for buffer of size {0}.",
                                                _receiveBufferSize, _incomingMessageSize));
                }
                // set up buffer for reading the message body.
                _bytesToReceive = _incomingMessageSize;
                BeginReceive();
                return(ServiceResult.Good);
            }

            // notify the sink.
            lock (_sinkLock) {
                if (_sink != null)
                {
                    try {
                        var messageChunk = new ArraySegment <byte>(_receiveBuffer, 0,
                                                                   _incomingMessageSize);
                        // Do not free the receive buffer now, it is freed in the stack.
                        _receiveBuffer = null;
                        // send notification
                        _sink.OnMessageReceived(this, messageChunk);
                    }
                    catch (Exception ex) {
                        Utils.Trace(ex,
                                    "Unexpected error invoking OnMessageReceived callback.");
                    }
                }
            }

            // free the receive buffer.
            if (_receiveBuffer != null)
            {
                _bufferManager.ReturnBuffer(_receiveBuffer, nameof(ProcessReceivedBuffer));
                _receiveBuffer = null;
            }
            // start receiving next message.
            ReceiveMessage();
            return(ServiceResult.Good);
        }
Esempio n. 59
0
        public ISubscriberConfigurator UseBufferManager(BufferManager bufferManager)
        {
            _bufferManager = bufferManager;

            return(this);
        }
Esempio n. 60
0
            //One of the two main entry points into the encoder. Called by WCF to encode a Message into a buffered byte array.
            public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                //Use the inner encoder to encode a Message into a buffered byte array
                ArraySegment <byte> buffer = innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);

                //Compress the resulting byte array
                return(CompressBuffer(buffer, bufferManager, messageOffset));
            }