protected int ReadByte() { var task = Stream.ReadAsync(RecvByte, 0, 1); task.Wait(); return(task.Result); }
static int _m_ReadAsync(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.Stream gen_to_be_invoked = (System.IO.Stream)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if (gen_param_count == 4 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)) { byte[] _buffer = LuaAPI.lua_tobytes(L, 2); int _offset = LuaAPI.xlua_tointeger(L, 3); int _count = LuaAPI.xlua_tointeger(L, 4); System.Threading.Tasks.Task <int> gen_ret = gen_to_be_invoked.ReadAsync( _buffer, _offset, _count); translator.Push(L, gen_ret); return(1); } if (gen_param_count == 5 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4) && translator.Assignable <System.Threading.CancellationToken>(L, 5)) { byte[] _buffer = LuaAPI.lua_tobytes(L, 2); int _offset = LuaAPI.xlua_tointeger(L, 3); int _count = LuaAPI.xlua_tointeger(L, 4); System.Threading.CancellationToken _cancellationToken; translator.Get(L, 5, out _cancellationToken); System.Threading.Tasks.Task <int> gen_ret = gen_to_be_invoked.ReadAsync( _buffer, _offset, _count, _cancellationToken); translator.Push(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } return(LuaAPI.luaL_error(L, "invalid arguments to System.IO.Stream.ReadAsync!")); }
/// <summary> /// 复制流 /// </summary> /// <param name="source">原始流</param> /// <param name="sourceLength">原始流长度</param> /// <param name="destination">目标流</param> /// <param name="bufferSize">分段复制流的大小</param> /// <param name="progress">进度</param> /// <param name="cancellationToken">取消标示</param> /// <returns></returns> public static async Task CopyToAsync(this System.IO.Stream source, long sourceLength, System.IO.Stream destination, long bufferSize = 81920, IProgress<double> progress = null, CancellationToken cancellationToken = default(CancellationToken)) { if (source == null) throw new ArgumentNullException(nameof(source)); if (!source.CanRead) throw new ArgumentException("Has to be readable", nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); if (!destination.CanWrite) throw new ArgumentException("Has to be writable", nameof(destination)); if (bufferSize < 0) throw new ArgumentOutOfRangeException(nameof(bufferSize)); var buffer = new byte[bufferSize]; var totalLength = (double) sourceLength; long totalBytesRead = 0; int bytesRead; while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); totalBytesRead += bytesRead; progress?.Report(totalBytesRead / totalLength); } }
private static int ReadIncomingMsgs() { Task <int> readTask = readStream?.ReadAsync(tempBytes, 0, tempBytes.Length, readCancellationToken.Token); TimeSpan ts = TimeSpan.FromMilliseconds(100); for (int i = 0; i < 150; i++) { if (shutDown) { readCancellationToken?.Cancel(); shutDown = true; return(-1); } if ((readTask?.IsCompleted ?? true) || (readTask?.Wait(ts) ?? true)) { break; } } if (readTask == null || !readTask.IsCompleted) { readCancellationToken?.Cancel(); shutDown = true; return(-1); } if (readTask.Status != TaskStatus.RanToCompletion) { shutDown = true; return(-1); } return(readTask.Result); }
/// <summary> /// Reads an http header as per the HTTP spec /// </summary> /// <param name="stream">The stream to read UTF8 text from</param> /// <param name="token">The cancellation token</param> /// <returns>The HTTP header</returns> public static async Task <string> ReadHttpHeaderAsync(System.IO.Stream stream, CancellationToken token) { int length = 1024 * 16; // 16KB buffer more than enough for http header byte[] buffer = new byte[length]; int offset = 0; int bytesRead = 0; do { if (offset >= length) { throw new EntityTooLargeException("Http header message too large to fit in buffer (16KB)"); } bytesRead = await stream.ReadAsync(buffer, offset, length - offset, token); offset += bytesRead; string header = Encoding.UTF8.GetString(buffer, 0, offset); // as per http specification, all headers should end this this if (header.Contains("\r\n\r\n")) { return(header); } } while (bytesRead > 0); return(string.Empty); }
async Task <JArray> DecodeStream(System.IO.Stream stream) { int expectedLength = 0, receivedLength = 1, readLength = 0; byte[] buffer = null; try { while (stream.CanRead) { if (expectedLength == 0) { expectedLength = GetSizeDescriptor(stream); readLength = receivedLength = 0; buffer = new byte[expectedLength]; } readLength = await stream.ReadAsync(buffer, Math.Max(readLength - 1, 0), expectedLength - receivedLength); receivedLength += readLength; if (receivedLength == expectedLength) { string received = validateData(buffer); _logger.Info("Received data : {0}", received); return(JArray.Parse(received)); } } } catch { throw new Exception("Decode stream error"); } return(new JArray()); }
async protected static void ReadThread(BluetoothService_test a, System.IO.Stream stm) { while (!cts.IsCancellationRequested) { try { byte[] at = new byte[1024]; Task <int> readTask = stm.ReadAsync(at, 0, 1024); using (cts.Token.Register(() => stm.Close())) { readTask.Wait(cts.Token); int iRead = await readTask; BTMessage msg = new BTMessage(); msg.type = 0; msg.length = iRead; msg.data = at; a.RecvMessage(a, msg); } } catch (System.OperationCanceledException) { //Handle the cancelled task. string text = int.MaxValue.ToString(); } catch (System.Exception e) { string text = e.ToString(); } } }
public async Task Copy(string asset) { System.IO.Stream source = openAsset(asset); File destinationFile = new File(externalDir, asset); destinationFile.ParentFile.Mkdir(); OutputStream destination = new FileOutputStream(destinationFile); byte[] buffer = new byte[1024]; int nread; System.Diagnostics.Debug.WriteLine(this.GetType().Name, $"Copying asset {destinationFile} to {asset}"); while ((nread = await source.ReadAsync(buffer, 0, buffer.Length)) > 0) { await destination.WriteAsync(buffer, 0, nread); await destination.FlushAsync(); } destination.Close(); System.Diagnostics.Debug.WriteLine(this.GetType().Name, $"DONE! Copied asset {asset} to {destinationFile}"); }
private async void ConvertImageToBase64String(System.IO.Stream stream) { var bytes = new byte[stream.Length]; await stream.ReadAsync(bytes, 0, (int)stream.Length); string base64 = Convert.ToBase64String(bytes); }
public ValueTask <StreamReadResult> ReadAsync(ArraySegment <byte> buffer) { if (buffer.Count == 0) { throw new Exception("Reading 0 bytes is not supported"); } var readTask = stream.ReadAsync(buffer.Array, buffer.Offset, buffer.Count); Task <StreamReadResult> transformedTask = readTask.ContinueWith(tt => { if (tt.Exception != null) { throw tt.Exception; } var res = tt.Result; return(new StreamReadResult { BytesRead = res, EndOfStream = res == 0, }); }); return(new ValueTask <StreamReadResult>(transformedTask)); }
private void ReadingThread() { byte[] buffer = new byte[1000]; while (true) { var task = stream.ReadAsync(buffer, 0, 1000); try { task.Wait(Token); } catch { break; } int len = task.Result; if (len > 0) { end = false; var chunk = System.Text.Encoding.UTF8.GetString(buffer, 0, len); reader.AddChunk(chunk); } else { Thread.Sleep(10); end = true; waiter.Set(); continue; } } }
internal async Task <FileSystemResult <IFile> > InternalCreateFile(DirectoryImplementation dir, string name, Stream readstream, CancellationToken token, IProgress <FileProgress> progress, Dictionary <string, object> properties) { if (properties == null) { properties = new Dictionary <string, object>(); } string path = name; if (dir.Parent != null) { path = Path.Combine(dir.FullName, path); } Stream s = File.Open(path, FileMode.Create, FileAccess.Write); byte[] block = new byte[1024 * 128]; long left = readstream.Length; do { int size = (int)Math.Min(left, block.Length); int rsize = await readstream.ReadAsync(block, 0, size, token); await s.WriteAsync(block, 0, rsize, token); left -= rsize; FileProgress p = new FileProgress { Percentage = ((float)(readstream.Length - left) * 100) / readstream.Length, TotalSize = readstream.Length, TransferSize = readstream.Length - left }; progress.Report(p); } while (left > 0 && !token.IsCancellationRequested); s.Close(); if (token.IsCancellationRequested) { try { File.Delete(path); } catch { // ignored } return(new FileSystemResult <IFile>("Transfer canceled")); } FileInfo finfo = new FileInfo(path); if (properties.Any(a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase))) { finfo.LastWriteTime = (DateTime)properties.First(a => a.Key.Equals("ModifiedDate", StringComparison.InvariantCultureIgnoreCase)).Value; } if (properties.Any(a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase))) { finfo.CreationTime = (DateTime)properties.First(a => a.Key.Equals("CreatedDate", StringComparison.InvariantCultureIgnoreCase)).Value; } LocalFile f = new LocalFile(finfo, FS); return(new FileSystemResult <IFile>(f)); }
static StackObject *ReadAsync_10(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 4); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @count = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Int32 @offset = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Byte[] @buffer = (System.Byte[]) typeof(System.Byte[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 4); System.IO.Stream instance_of_this_method = (System.IO.Stream) typeof(System.IO.Stream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.ReadAsync(@buffer, @offset, @count); object obj_result_of_this_method = result_of_this_method; if (obj_result_of_this_method is CrossBindingAdaptorType) { return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance)); } return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public static async Task <byte[]> ReadBytesAsync(this System.IO.Stream stream) { var buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length); return(buffer); }
public async Task <HttpWebResponse> RequstHttp(string method, string uri, Dictionary <string, string> parameter, string Token, System.IO.Stream filestream, long maxsize = 0, int blocksize = 0) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; string requsturi = uri; if (parameter != null) { requsturi = HttpHelper.HttpParameter(uri, parameter); } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requsturi); request.Method = method; request.UserAgent = "AllCloude"; request.Accept = "application/json"; request.Headers["Authorization"] = "Bearer " + Token; request.Timeout = Timeout.Infinite; request.ReadWriteTimeout = Timeout.Infinite; request.SendChunked = true; request.Headers["Content-Range"] = string.Format("bytes 0-{0}/{1}", maxsize - 1, maxsize); request.ContentLength = maxsize; request.ContentType = "application/json"; int readsize = 0; byte[] buf = new byte[blocksize]; long presize = 0; long totalsize = 0; System.IO.Stream stream = await request.GetRequestStreamAsync(); while ((readsize = await filestream.ReadAsync(buf, 0, blocksize, CancellationToken.None)) > 0) { await stream.WriteAsync(buf, 0, readsize, CancellationToken.None); presize += readsize; totalsize += readsize; this.OnProgressChange(this, maxsize, totalsize, this.progress); } stream.Close(); HttpWebResponse respone = null; try { respone = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Response != null) { Dictionary <string, object> di = HttpHelper.DerealizeJson(e.Response.GetResponseStream()); } throw e; } catch (Exception e) { throw e; } return(respone); }
public async static Task <byte[]> ToByteArrayAsync(this System.IO.Stream stream) { Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length); byte[] buffer = new Byte[length]; await stream.ReadAsync(buffer, 0, length); return(buffer); }
private static async Task <string> ReadDataFromStream(System.IO.Stream stream) { const int bufferOffset = 0; byte[] bytes = new byte[MaxContentSize]; int bytesCount = await stream.ReadAsync(bytes, bufferOffset, MaxContentSize); return(Encoding.UTF8.GetString(bytes, 0, bytesCount)); }
public static async Task <string> ReadAsync(System.IO.Stream stream) { var sb = new System.Text.StringBuilder(); int bytesRead; while ((bytesRead = await stream.ReadAsync(_buffer, 0, _buffer.Length).ConfigureAwait(false)) > 0) { sb.Append(System.Text.Encoding.UTF8.GetString(_buffer, 0, bytesRead)); } return(sb.ToString()); }
public virtual void SendDataFromIOStream(System.IO.Stream ioStream, CancellationToken cancel) { Interlocked.Increment(ref UseCount); Task.Run(async() => { // We use the same default buffer size as System.IO.Stream.CopyToAsync() // TODO: Should this depend on the transport packet size? (Slic default packet size is 32KB for // example). int bufferSize = 81920; if (ioStream.CanSeek) { long remaining = ioStream.Length - ioStream.Position; if (remaining > 0) { // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } ArraySegment <byte> receiveBuffer = ArrayPool <byte> .Shared.Rent(bufferSize); try { var sendBuffers = new List <ArraySegment <byte> > { receiveBuffer }; int received; do { try { TransportHeader.CopyTo(receiveBuffer); received = await ioStream.ReadAsync(receiveBuffer.Slice(TransportHeader.Length), cancel).ConfigureAwait(false); sendBuffers[0] = receiveBuffer.Slice(0, TransportHeader.Length + received); await SendAsync(sendBuffers, received == 0, cancel).ConfigureAwait(false); } catch { await ResetAsync((long)StreamResetErrorCode.StopStreamingData).ConfigureAwait(false); break; } }while (received > 0); } finally { ArrayPool <byte> .Shared.Return(receiveBuffer.Array !); } TryDispose(); ioStream.Dispose(); }, cancel); }
/// <summary> /// Lê os dados de forma assincrona. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_consumed >= _contentLength) { return(0); } var maxRead = (int)Math.Min(count, _contentLength - _consumed); int read = await _stream.ReadAsync(buffer, offset, maxRead, cancellationToken); _consumed += read; return(read); }
public async Task <HttpResponseMessage> GetDownloadDocument(int id, string token) { HttpResponseMessage response = Request.CreateResponse(); var doc = await db.Documents.FindAsync(id); if (doc == null) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } //Create a WebRequest to get the file HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create( Helpers.FileServerTokenManager.GetFullPath(doc.FileServer, doc.FilePath) ); //Create a response for this request HttpWebResponse fileResp = (HttpWebResponse)await fileReq.GetResponseAsync(); var length = (int)fileResp.ContentLength; /*TODO: Currently we load all the response content into buffer (server memory). * In future, We may do this only partially for a bytes block and stream continously to the response*/ byte[] buffer = new byte[length]; using (System.IO.Stream stream = fileResp.GetResponseStream()) { int remaining = length; int pos = 0; while (remaining != 0) { int add = await stream.ReadAsync(buffer, pos, remaining); pos += add; remaining -= add; } } var outbuffer = Helpers.EncryptionService.DecryptBytes(buffer, doc.BF_Idx); var outStream = new System.IO.MemoryStream(outbuffer); response.Content = new StreamContent(outStream); response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("render"); response.Content.Headers.ContentDisposition.FileName = string.Format( "doc_{0}_{1}.jpg", doc.Id, System.IO.Path.GetFileNameWithoutExtension(doc.FilePath) ); response.Content.Headers.ContentLength = outbuffer.Count(); return(response); }
private static async Task CheckForDataRemainingOnTheStream(System.IO.Stream stream) { int bufferOffset = 0; byte[] remainingData = new byte[1]; int bytesStillToRead = await stream.ReadAsync(remainingData, bufferOffset, 1); if (bytesStillToRead > 0) { // Log error Console.WriteLine($"Size of http response body exceeds {MaxContentSize} bytes, the response has been truncated"); } }
public static async Task SetData(this Attachment att, System.IO.Stream stream, long length) { var data = new byte[length]; int pos = 0, step = 1000; while (pos < length && await stream.ReadAsync(data, pos, Math.Min(step, (int)(length - pos))) > 0) { pos += step; } ; att.SetData(data); }
protected async System.Threading.Tasks.Task <System.Text.Json.JsonDocument?> ParseJsonFromFile(Microsoft.Extensions.FileProviders.IFileProvider fileProvider, string fileName) { using System.IO.Stream stream = fileProvider.GetFileInfo(fileName).CreateReadStream(); byte[] buffer = new byte[stream.Length]; _ = await stream.ReadAsync(buffer, 0, buffer.Length); try { return(System.Text.Json.JsonDocument.Parse(new System.Buffers.ReadOnlySequence <byte>(buffer))); } catch (System.Text.Json.JsonException) { return(null); } }
public async void ReadGetIngridients(int runTime, List <Container> containerList) { byte[] mmBuffer = new byte[1024]; int numBytes; // bytes returned from read() Stopwatch timer = new Stopwatch(); timer.Start(); while (true) { try { System.Console.WriteLine("reciving..."); if (timer.ElapsedMilliseconds >= runTime || containerList.Count > 5) { break; } numBytes = await mInStream.ReadAsync(mmBuffer, 0, mmBuffer.Length); // Send the obtained bytes to the UI activity. if (numBytes > 0) { string recivedMessage = ASCIIEncoding.ASCII.GetString(mmBuffer); System.Console.WriteLine(recivedMessage); DeSerialize.DeSerializeArray(recivedMessage, containerList, this); } } catch (System.IO.IOException e) { System.Console.WriteLine("InputStream failure ERROR:4084"); System.Console.WriteLine(e.Message); throw; } } }
public async Task <CheckInMessage> WaitForCheckIn() { if (stream != null) { var bytes = new byte[Message.HeaderSize]; if (await stream.ReadAsync(bytes, 0, Message.HeaderSize) > 0) { var message = new MessageInfo(bytes); if (message.Type == MessageType.CheckIn) { return(new CheckInMessage(MessagePacket.Parse(message, stream))); } } } return(default);
public async Task <InputReport> GetInputReport(byte reportId = 0) { byte[] tmp = null; if (AccessLevel == HidDeviceAccess.Read) { tmp = manager.GetInputReport(handle, capabilities.InputReportByteLength); } else { tmp = new byte[capabilities.InputReportByteLength]; await stream.ReadAsync(tmp, 0, tmp.Length).WithTimeout(TimeSpan.FromMilliseconds(500)); } return(new InputReport(tmp)); }
public async static Task <string> PCLStorageLoad(string folderName, string fileName) { IFolder rootFolder = FileSystem.Current.LocalStorage; IFolder folder = await rootFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); IFile file = await folder.GetFileAsync(fileName); byte[] buffer; using (System.IO.Stream stream = await file.OpenAsync(FileAccess.Read)) { buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, (int)stream.Length); } return(System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length)); }
protected async Task <bool> TryReadAsync(TcpClient client, System.IO.Stream stream, byte[] buffer, int length, CancellationToken token) { int readBytes = 0; while (readBytes < length) { if (token.IsCancellationRequested || !client.IsConnected()) { return(false); } readBytes += await stream.ReadAsync(buffer, readBytes, length - readBytes, token); } return(true); }
public static async Task <int> ReadBlockAsync(this System.IO.Stream stream, byte[] buffer, int offset, int count) { int bufferLength = 0; while (bufferLength < count) { int readLength = await stream.ReadAsync(buffer, offset + bufferLength, count - bufferLength).ConfigureAwait(false); if (readLength == 0) { break; } bufferLength += readLength; } return(bufferLength); }