public void Dispose() { if (IsDisposed) { return; } _pingPongTimer?.Stop(); _authTimer?.Stop(); if (_messageReader != null) { _messageReader.PacketReceived -= ClientOnPacketReceived; _messageReader.StreamClosed -= MessageReaderOnStreamClosed; } _messageReader?.Close(); _messageWriter?.Close(); _client?.Close(); IsDisposed = true; }
private void ConstructAndSendMessages(ReflectInsightPackage[] messages) { if (DateTime.Now.Subtract(LastUnsuccessfulConnection).TotalSeconds < LastUnsuccessfulWaitTime) { // The last successful connection was less than the specified time, just return. // We need to try again later return; } // serialize the packages to a binary blob Byte[] bData = null; using (var pool = FastFormatterPool.Pool.Container()) { bData = FastSerializerEnumerable <ReflectInsightPackage> .Serialize(pool.Instance, messages); } ListenerRequest.DecompressedLength = 0; if (bData.Length > MessageRequestConstants.MAX_COMPRESSION) { ListenerRequest.DecompressedLength = bData.Length; // compress data using (var ms = new MemoryStream()) { using (GZipStream msCompressed = new GZipStream(ms, CompressionMode.Compress)) { msCompressed.Write(bData, 0, bData.Length); } bData = ms.ToArray(); } } ListenerRequest.RequestId = CryptoServices.RandomIdToUInt64(); ListenerRequest.SequenceCount = (Int16)((bData.Length / MessageRequestConstants.MAX_CHUNKSIZE) + ((bData.Length % MessageRequestConstants.MAX_CHUNKSIZE) > 0 ? 1 : 0)); try { if (!MessageWriter.IsOpen()) { MessageWriter.Open(); } try { WriteRequest(MessageRequestType.Request, ListenerRequest); // now send data in chunks if larger than 3 MB Int16 nextSequence = 1; Int32 atSource = 0; Int32 remaining = bData.Length; Int32 chunkSize = remaining < MessageRequestConstants.MAX_CHUNKSIZE ? remaining : MessageRequestConstants.MAX_CHUNKSIZE; while (remaining > 0) { Byte[] bChunk = new Byte[chunkSize]; Array.Copy(bData, atSource, bChunk, 0, bChunk.Length); atSource += chunkSize; remaining -= chunkSize; chunkSize = remaining < MessageRequestConstants.MAX_CHUNKSIZE ? remaining : MessageRequestConstants.MAX_CHUNKSIZE; MessageSequence sequence = new MessageSequence(); sequence.SessionId = ListenerRequest.SessionId; sequence.RequestId = ListenerRequest.RequestId; sequence.Sequence = nextSequence++; sequence.Chunk = bChunk; WriteRequest(MessageRequestType.Sequence, sequence); } } finally { if (!MessageWriter.IsThreadSafe()) { MessageWriter.Close(); } } } catch (Exception) { LastUnsuccessfulConnection = DateTime.Now; throw; } }