public async void ReadClientData(IAsyncResult ar) { try { if (!Client.Connected) { Disconnected(); } else { int Recevied = Client.EndReceive(ar); if (Recevied > 0) { if (BufferRecevied == false) { if (Buffer[0] == 0) { Buffersize = Convert.ToInt64(Encoding.UTF8.GetString(MS.ToArray())); MS.Dispose(); MS = new MemoryStream(); if (Buffersize > 0) { Buffer = new byte[Buffersize - 1]; BufferRecevied = true; } } else { await MS.WriteAsync(Buffer, 0, Buffer.Length); } } else { await MS.WriteAsync(Buffer, 0, Recevied); if (MS.Length == Buffersize) { // Read.BeginInvoke(this, MS.ToArray(), null, null); await Task.Run(() => { HandlePacket.Read(this, MS.ToArray()); Settings.Received += MS.ToArray().Length; Buffer = new byte[1]; Buffersize = 0; MS.Dispose(); MS = new MemoryStream(); BufferRecevied = false; }); } else { Buffer = new byte[Buffersize - MS.Length]; } } Client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, ReadClientData, null); } else { Disconnected(); } } } catch { Disconnected(); } }