public static async Task CopyStreamAsync(this Stream input, Stream output, Int32?position, IProgress <Int64> progress, CancellationToken token) { if (output is null) { throw new ArgumentNullException(nameof(output)); } Byte[] buffer = new Byte[BufferUtils.DefaultBuffer]; if (position.HasValue && input.CanSeek) { input.Position = position.Value; } Int32 read; Int64 already = 0; while ((read = await input.ReadAsync(buffer.AsMemory(0, buffer.Length), token).ConfigureAwait(false)) > 0) { await output.WriteAsync(buffer.AsMemory(0, read), token).ConfigureAwait(false); already += read; progress?.Report(already); } }
public static void Encode( Stream input, TextWriter output, Func <ReadOnlyMemory <Byte>, Boolean, String> bufferEncodeFunc, Int32 bufferSize = BufferUtils.DefaultBuffer) { Byte[] buffer = new Byte[bufferSize]; while (true) { Int32 bytesRead = input.Read(buffer, 0, bufferSize); if (bytesRead < 1) { break; } String result = bufferEncodeFunc(buffer.AsMemory(0, bytesRead), bytesRead < bufferSize); output.Write(result); } }
public static async Task EncodeAsync( Stream input, TextWriter output, Func <ReadOnlyMemory <Byte>, Boolean, String> bufferEncodeFunc, Int32 bufferSize = BufferUtils.DefaultBuffer) { Byte[] buffer = new Byte[bufferSize]; while (true) { Int32 bytesRead = await input.ReadAsync(buffer, 0, bufferSize).ConfigureAwait(false); if (bytesRead < 1) { break; } String result = bufferEncodeFunc(buffer.AsMemory(0, bytesRead), bytesRead < bufferSize); await output.WriteAsync(result).ConfigureAwait(false); } }
public static async Task Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Usage: swvo-websocket-terminator SessId Host:Port BookmarkName LocalPort"); Console.WriteLine("Example: swvo-websocket-terminator 44E4224D3E4B1C74FCADE675803C1162 sonicwall.company.com:4433 SSH 2222"); return; } var sessId = args[0]; var hostPort = args[1]; var bookmarkName = args[2]; var localPort = Int32.Parse(args[3]); var domain = hostPort.Split(':')[0]; var socket = new ClientWebSocket(); socket.Options.AddSubProtocol("binary"); socket.Options.Cookies = new CookieContainer(); socket.Options.Cookies.Add(new Cookie("SessId", sessId) { Domain = domain }); try { await socket.ConnectAsync(new Uri($"wss://{hostPort}/ws?bookmark={WebUtility.UrlEncode(bookmarkName)}"), default); } catch { Console.WriteLine("Unable to connect to server"); return; } Console.WriteLine("Connected to server"); var tl = new TcpListener(IPAddress.Loopback, localPort); tl.Start(); Console.WriteLine("Waiting for local connection"); var client = await tl.AcceptTcpClientAsync(); Console.WriteLine("Starting IO tasks"); var t1 = Task.Run(async() => { var buffer = new Byte[16777216]; var i = client.GetStream(); Int32 bytesRead; while ((bytesRead = i.Read(buffer)) > 0) { //Trace.WriteLine($"{bytesRead} to server"); await socket.SendAsync(buffer.AsMemory(0, bytesRead), WebSocketMessageType.Binary, true, default); } }); var t2 = Task.Run(async() => { var buffer = new Byte[16777216]; var o = client.GetStream(); WebSocketReceiveResult result; while ((result = await socket.ReceiveAsync(buffer, default)).Count > 0) { //Trace.WriteLine($"{result.Count} to client"); o.Write(buffer.AsSpan(0, result.Count)); } }); try { await t1; await t2; } catch { // Don't care. } Console.WriteLine("Program complete"); }
public async Task Download(Uri uri, String filePath) { try { _bytesLastUpdate = 0; _nextUpdate = DateTime.UtcNow.AddSeconds(1); // Determine the file size var webRequest = WebRequest.Create(uri); webRequest.Method = "HEAD"; webRequest.Timeout = 5000; Int64 responseLength; using (var webResponse = await webRequest.GetResponseAsync()) { responseLength = Int64.Parse(webResponse.Headers.Get("Content-Length")); } var timeout = DateTimeOffset.UtcNow.AddHours(1); while (timeout > DateTimeOffset.UtcNow && !_cancelled) { try { var request = WebRequest.Create(uri); using var response = await request.GetResponseAsync(); await using var stream = response.GetResponseStream(); if (stream == null) { throw new IOException("No stream"); } await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write); var buffer = new Byte[64 * 1024]; while (fileStream.Length < response.ContentLength && !_cancelled) { var read = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length)); if (read > 0) { fileStream.Write(buffer, 0, read); BytesDone = fileStream.Length; BytesTotal = responseLength; if (DateTime.UtcNow > _nextUpdate) { Speed = fileStream.Length - _bytesLastUpdate; _nextUpdate = DateTime.UtcNow.AddSeconds(1); _bytesLastUpdate = fileStream.Length; timeout = DateTimeOffset.UtcNow.AddHours(1); DownloadProgressChanged?.Invoke(this, new DownloadProgressChangedEventArgs(null) { BytesPerSecondSpeed = Speed, ProgressedByteSize = _bytesLastUpdate, TotalBytesToReceive = BytesTotal, AverageBytesPerSecondSpeed = Speed, ReceivedBytesSize = BytesDone, }); } } else { break; } } break; } catch (IOException) { await Task.Delay(1000); } catch (WebException) { await Task.Delay(1000); } } if (timeout <= DateTimeOffset.UtcNow) { throw new Exception($"Download timed out"); } DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(null, false, null)); } catch (Exception ex) { DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(ex, false, null)); } }