public void WriteAsync(SocketEventArgs args) { NSOutputStream stream = GetStreamForConnectionConext(args); if (stream == null) { // OnCompleted called in GetStreamForConnectionConext(), just return here. return; } try { EventHandler <NSStreamEventArgs> handler = null; handler = (_, e1) => { stream.OnEvent -= handler; if (e1.StreamEvent == NSStreamEvent.ErrorOccurred) { args.SocketException = new Exception("Something unexpected happened. " + e1.StreamEvent.ToString()); args.Complete(); } if (e1.StreamEvent != NSStreamEvent.HasSpaceAvailable) { return; } WriteAsyncInternal(stream, args); }; if (stream.HasSpaceAvailable()) { WriteAsyncInternal(stream, args); } else { stream.OnEvent += handler; } } catch (ObjectDisposedException) { // Effectively ignoring this args.Complete(); } catch (Exception ex) { args.SocketException = new Exception("Unable to write to the TCP connection. See inner exception for details.", ex); args.Complete(); } }
public void Write(byte[] buffer, int offset, int count) { if (offset < 0) { throw new ArgumentException("Offset must be greater than or equal to 0"); } var bytesSent = 0; var bytesToBeSent = new byte[buffer.Length - offset]; var length = count; buffer.CopyTo(bytesToBeSent, offset); Console.WriteLine($"Start writing to stream - length: {buffer.LongLength}"); while (length > 0) { if (_outputStream.HasSpaceAvailable()) { var bytesWritten = _outputStream.Write(buffer, (uint)count); if (bytesWritten == -1) { Console.WriteLine($"{buffer.LongLength} bytes failed to write to stream"); break; } if (bytesWritten > 0) { Console.WriteLine($"Bytes written to stream: {bytesWritten}"); length -= (int)bytesWritten; if (0 == length) { break; } var temp = new List <byte>(); for (var i = bytesWritten; i < bytesToBeSent.Length; i++) { temp.Add(bytesToBeSent[i]); } bytesToBeSent = temp.ToArray(); } } else { Console.WriteLine("No more space left in output stream"); } } }
IObservable<Unit> SaveFullResolutionImageToFile (FileRequest request) { return Observable.Create<Unit> (o => { var description = request.DescriptionAs<AssetDescription> (); var disp = new CancellationDisposable (); var token = disp.Token; GetAsset (description, token).ContinueWith (t => { using (File.Create (request.Filename)) using (var asset = t.Result) using (var representation = asset.DefaultRepresentation) using (var stream = new NSOutputStream (request.Filename, true)) { stream.Open (); long offset = 0; uint bytesRead = 0; NSError err; // A large enough buffer that shouldn't cause memory warnings byte [] buffer = new byte [131072]; GCHandle handle = GCHandle.Alloc (buffer, GCHandleType.Pinned); IntPtr pointer = handle.AddrOfPinnedObject (); unsafe { while (offset < representation.Size && stream.HasSpaceAvailable ()) { bytesRead = representation.GetBytes (pointer, offset, (uint)buffer.Length, out err); stream.Write (buffer, bytesRead); offset += bytesRead; } } stream.Close (); handle.Free (); } o.OnCompleted (); }, token).RouteExceptions (o); return disp; }); }