public Task StartAsync() { return(Task.Factory.StartNew(() => { try { Console.WriteLine("Ping service started"); while (_fluffyNetClient.TcpClient.Connected) { Thread.Sleep(_pingInterval); _fluffyNetClient.Send(PingData); } } catch (Exception e) { Console.WriteLine("Ping service interrupted"); _fluffyNetClient.CloseConnect(); } })); }
public void Run(int receiveBufferLength = 4096) { try { using (NetworkStream stream = _client.GetStream()) { while (_client.Connected) { if (_client.Available < HeaderLength) { Thread.Sleep(5); continue; } int messageLength = ReceiveHeaderData(stream); int remaining = messageLength; byte[] finalDataBuffer = new byte[messageLength]; int index = 0; while (remaining > 0) { if (remaining < receiveBufferLength) { receiveBufferLength = remaining; } while (_client.Available < receiveBufferLength) { Thread.Sleep(5); } byte[] buffer = new byte[receiveBufferLength]; stream.Read(buffer, 0, receiveBufferLength); for (int i = 0; i < buffer.Length; i++) { finalDataBuffer[index++] = buffer[i]; } remaining -= receiveBufferLength; } if (_fluffyNetClient.Aes256Key != null) { finalDataBuffer = MyAes.DecryptBytes(finalDataBuffer, _fluffyNetClient.Aes256Key, MyAes.Iv); } Console.WriteLine("Readed data from socket " + finalDataBuffer.Length + " bytes"); if (!ByteArrayCompare(PongData, finalDataBuffer)) { NewData?.Invoke(finalDataBuffer); } } } } catch (Exception e) { // Debug Console.WriteLine(e.Message + " " + e.StackTrace); } finally { _fluffyNetClient.CloseConnect(); Disconnected?.Invoke(_fluffyNetClient); } }