void dataRead(IAsyncResult result) { byte[] buffer = result.AsyncState as byte[]; string data = ASCIIEncoding.ASCII.GetString(buffer, 0, buffer.Length); TransmitedDataType datatype = TransmitedDataType.Unknown; data = data.TrimEnd(); if (data.Length > 4 && data.StartsWith("C")) { datatype = data.StartsWith("C101") ? TransmitedDataType.Message : data.StartsWith("C102") ? TransmitedDataType.Status : data.StartsWith("C103") ? TransmitedDataType.Command : data.StartsWith("C104") ? TransmitedDataType.Headers : data.StartsWith("C105") ? TransmitedDataType.RawData : TransmitedDataType.Unknown; if (datatype == TransmitedDataType.Status) { var stateID = Enum.Parse(typeof(NetworkStates), data.Substring(4)); if (stateID is NetworkStates) { ServerState = (NetworkStates)stateID; if (ServerState == NetworkStates.Disconnected) { StopReceiving(); State = NetworkStates.Disconnected; ServerState = NetworkStates.Disconnected; connected = false; client.Close(); if (OnServerDisconnected != null) { OnServerDisconnected.Invoke(); } } // return; } } if (datatype != TransmitedDataType.Unknown) { data = data.Substring(4); } } latestReceivedData = data; if (OnDataReceived != null) { OnDataReceived.Invoke(data, datatype); } if (!stopReceiver) { buffer = new byte[BufferSize]; connectionStream.BeginRead(buffer, 0, BufferSize, dataRead, buffer); } }
public void ReadElementAsync() { try { var buffer = new byte[1024]; stream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer); } catch (Exception ex) { OnError(this, ex); } }
public IAsyncResult BeginRead(System.IO.Stream stream, AsyncCallback callback, object state) { _forceNewRead = false; if (_offset == _available) { _offset = 0; _available = 0; } else if (_buffer.Length - _available < _bufferSize) { if (_buffer.Length - (_available - _offset) < _bufferSize) { var buffer = new byte[_buffer.Length * 2]; Array.Copy(_buffer, _offset, buffer, 0, _available - _offset); _buffer = buffer; } else { Array.Copy(_buffer, _offset, _buffer, 0, _available - _offset); } _available -= _offset; _offset = 0; } int bufferAvailable = Math.Min(_buffer.Length - _available, _bufferSize); return(stream.BeginRead(_buffer, _available, bufferAvailable, callback, state)); }
void TransparentStreamReadRequestMessageReceived(TransparentStreamMessageBase transparentStreamMessageBase) { TransparentStreamReadRequestMessage request = (TransparentStreamReadRequestMessage)transparentStreamMessageBase; byte[] buffer = new byte[request.Count]; try { baseStream.BeginRead(buffer, 0, request.Count, (ar) => { try { int bytesRead = baseStream.EndRead(ar); if (bytesRead != ((byte[])ar.AsyncState).Length) { byte[] newBuffer = new byte[bytesRead]; System.Buffer.BlockCopy((byte[])ar.AsyncState, 0, newBuffer, 0, bytesRead); objectBusSession.SendMessage(new TransparentStreamReadResponseMessage(streamID, request.ID, newBuffer, null)); } else { objectBusSession.SendMessage(new TransparentStreamReadResponseMessage(streamID, request.ID, (byte[])ar.AsyncState, null)); } } catch (Exception ex) { objectBusSession.SendMessage(new TransparentStreamReadResponseMessage(streamID, request.ID, (byte[])ar.AsyncState, ex)); } }, buffer); } catch (Exception ex) { objectBusSession.SendMessage(new TransparentStreamReadResponseMessage(streamID, request.ID, null, ex)); } }
private void CheckRead() { if (_stream == null) { return; } if (_async != null) { if (_async.IsCompleted) { _readCount = _stream.EndRead(_async); _readOffset = 0; //Debug.Log("EndRead {0}", _readCount); _async = null; if (_readCount > 0) { LastTime = System.DateTime.Now; } } } else if (Available == 0) { //Debug.Log("BeginRead"); _async = _stream.BeginRead(_readBuffer, 0, _readBuffer.Length, null, null); } }
void Reader() { try { readAsyncResult = networkStream.BeginRead(readBuffer, 0, 6, new AsyncCallback((asyncResult) => { if (readAsyncResult != asyncResult) { return; } lock (sentLock) { try { var bytesRead = networkStream.EndRead(asyncResult); if (bytesRead > 0) { //We now expect apple to close the connection on us anyway, so let's try and close things // up here as well to get a head start //Hopefully this way we have less messages written to the stream that we have to requeue try { stream.Close(); } catch { } try { stream.Dispose(); } catch { } try { client.Client.Shutdown(SocketShutdown.Both); } catch { } try { client.Client.Dispose(); } catch { } try { client.Close(); } catch { } client = null; stream = null; //Get the enhanced format response // byte 0 is always '1', byte 1 is the status, bytes 2,3,4,5 are the identifier of the notification var status = readBuffer[1]; var identifier = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(readBuffer, 2)); HandleFailedNotification(identifier, status); //Start reading again Reader(); } else { connected = false; } } catch { connected = false; } } // End Lock }), null); } catch { connected = false; } }
public void downloading(IAsyncResult res) { int read = 0; try { read = response_stream.EndRead(res); } catch (Exception e) { failure("Error receving response from server after saving file", e); return; } if (read > 0) { downloaded += read; if (downloaded < buffer.Length) { try { response_stream.BeginRead(buffer, downloaded, buffer.Length - downloaded, downloading, this); } catch (Exception e) { failure("Error receving response from server after saving file", e); } return; } } try { response_stream.Close(); response_stream = null; } catch (Exception) { } string resp = System.Text.Encoding.UTF8.GetString(buffer, 0, downloaded); if (resp.Equals("OK")) { saved = true; } else { failure("Error saving file: " + resp, null); } }
static void StreamReadCallback(IAsyncResult ar) { var This = (GetResponse)ar.AsyncState; System.IO.Stream stream = null; try { stream = This.resp.GetResponseStream(); var szRead = stream.EndRead(ar); if (szRead > 0) { This.outputStream.Write(This.temp, 0, szRead); stream.BeginRead(This.temp, 0, This.temp.Length, StreamReadCallback, This); } else { This.SetResponded(This.resp.StatusCode, This.resp.StatusDescription, This.resp.Cookies, This.resp.Headers); stream.Close(); stream.Dispose(); stream = null; This.resp.Close(); This.resp = null; } } catch (System.Exception e) { if (stream != null) { stream.Close(); stream.Dispose(); stream = null; } This.SetRespondedWithClientError(e); } }
static int _m_BeginRead(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.Stream gen_to_be_invoked = (System.IO.Stream)translator.FastGetCSObj(L, 1); { byte[] _buffer = LuaAPI.lua_tobytes(L, 2); int _offset = LuaAPI.xlua_tointeger(L, 3); int _count = LuaAPI.xlua_tointeger(L, 4); System.AsyncCallback _callback = translator.GetDelegate <System.AsyncCallback>(L, 5); object _state = translator.GetObject(L, 6, typeof(object)); System.IAsyncResult gen_ret = gen_to_be_invoked.BeginRead( _buffer, _offset, _count, _callback, _state); translator.PushAny(L, gen_ret); return(1); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
void Reader() { try { networkStream.BeginRead(readBuffer, 0, 6, new AsyncCallback((asyncResult) => { lock (sentLock) { try { var bytesRead = networkStream.EndRead(asyncResult); if (bytesRead > 0) { Log.Info("in Reader bytes read {0}", bytesRead); //We now expect apple to close the connection on us anyway, so let's try and close things // up here as well to get a head start //Hopefully this way we have less messages written to the stream that we have to requeue try { stream.Close(); stream.Dispose(); } catch { } try { client.Close(); stream.Dispose(); } catch { } //Get the enhanced format response // byte 0 is always '1', byte 1 is the status, bytes 2,3,4,5 are the identifier of the notification var status = readBuffer[1]; var identifier = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(readBuffer, 2)); HandleFailedNotification(identifier, status); //Start reading again Reader(); //connected = false; } else { Log.Warning("Read 0 bytes, perhaps this is the signal to close the stream. Shutting down client and the bunch."); try { stream.Close(); stream.Dispose(); } catch { } try { client.Close(); stream.Dispose(); } catch { } connected = false; } } catch { connected = false; } } // End Lock }), null); } catch { connected = false; } }
public void startReceive(IAsyncResult res) { try { response = (HttpWebResponse)request.EndGetResponse(res); response_stream = response.GetResponseStream(); response_stream.BeginRead(buffer, 0, buffer.Length, downloading, this); } catch (Exception e) { failure("Error receiving response from server after upload", e); } }
void GetResponseCallback(IAsyncResult asyncResult) { try { WebResponse = WebRequest.EndGetResponse(asyncResult); Stream = WebResponse.GetResponseStream(); BufferOffset = 0; Stream.BeginRead(Buffer, BufferOffset, Buffer.Length, ReadCallback, null); } catch (System.Exception e) { Exception = e; } }
public void startReceive(IAsyncResult res) { try { download_response = (HttpWebResponse)download_request.EndGetResponse(res); total = (int)download_response.ContentLength; downloaded = 0; onprogress(null, 0, total, 0); stream = download_response.GetResponseStream(); stream.BeginRead(buffer, 0, 65536, downloading, this); } catch (Exception e) { failure("Error " + action, e); } }
void Reader() { try { var result = networkStream.BeginRead(readBuffer, 0, 6, new AsyncCallback((asyncResult) => { lock (sentLock) { try { var bytesRead = networkStream.EndRead(asyncResult); if (bytesRead > 0) { disconnect(); //Get the enhanced format response // byte 0 is always '1', byte 1 is the status, bytes 2,3,4,5 are the identifier of the notification var status = readBuffer[1]; var identifier = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(readBuffer, 2)); HandleFailedNotification(identifier, status); //Start reading again Reader(); } else { connected = false; } } catch { connected = false; } } // End Lock }), null); } catch { connected = false; } }
void ReadCallback(IAsyncResult asyncResult) { try { var size = Stream.EndRead(asyncResult); if (size <= 0) { var ip = System.Text.Encoding.ASCII.GetString(Buffer); IPAddress = IPAddress.Parse(ip); return; } BufferOffset += size; Stream.BeginRead(Buffer, BufferOffset, Buffer.Length - BufferOffset, ReadCallback, null); } catch (System.Exception e) { Exception = e; } }
public void downloading(IAsyncResult res) { int read; try { read = stream.EndRead(res); } catch (Exception e) { failure("Error " + action, e); return; } if (read > 0) { downloaded += read; onprogress(buffer, read, total, downloaded); try { stream.BeginRead(buffer, 0, 65536, downloading, this); } catch (Exception e) { failure("Error " + action, e); } return; } try { stream.Close(); stream = null; } catch (Exception) { } onsuccess(); }
void Reader() { try { var result = networkStream.BeginRead(readBuffer, 0, 6, new AsyncCallback((asyncResult) => { lock (sentLock) { try { var bytesRead = networkStream.EndRead(asyncResult); if (bytesRead > 0) { //We now expect apple to close the connection on us anyway, so let's try and close things // up here as well to get a head start //Hopefully this way we have less messages written to the stream that we have to requeue try { stream.Close(); stream.Dispose(); } catch { } try { client.Close(); stream.Dispose(); } catch { } //Get the enhanced format response // byte 0 is always '1', byte 1 is the status, bytes 2,3,4,5 are the identifier of the notification var status = readBuffer[1]; var identifier = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(readBuffer, 2)); int failedNotificationIndex = -1; SentNotification failedNotification = null; //Try and find the failed notification in our sent list for (int i = 0; i < sentNotifications.Count; i++) { var n = sentNotifications[i]; if (n.Identifier.Equals(identifier)) { failedNotificationIndex = i; failedNotification = n; break; } } //Don't bother doing anything unless we know what failed if (failedNotification != null && failedNotificationIndex > -1) { //Anything before the failed message must have sent OK // so let's expedite the success status Success for all those before the failed one if (failedNotificationIndex > 0) { for (int i = 0; i < failedNotificationIndex; i++) { this.Events.RaiseNotificationSent(sentNotifications[i].Notification); } } //The notification that failed needs to have a failure event raised // we don't requeue it because apple told us it failed for real this.Events.RaiseNotificationSendFailure(failedNotification.Notification, new NotificationFailureException(status, failedNotification.Notification)); // finally, raise failure for anything after the index of this failed one // in the sent list, since we may have sent them but apple will have disregarded // anything after the failed one and not told us about it if (failedNotificationIndex < sentNotifications.Count - 1) { //Requeue the failed notification since we're not sure it's a bad // notification, just that it was sent after a bad one was for (int i = failedNotificationIndex + 1; i <= sentNotifications.Count - 1; i++) { this.QueueNotification(sentNotifications[i].Notification, false); } } //Now clear out the sent list since we processed them all manually above sentNotifications.Clear(); } //Start reading again Reader(); } else { connected = false; } } catch { connected = false; } } // End Lock }), null); } catch { connected = false; } }
public override void recv(byte[] buffer, int offset, int size, ResultHandler rh) { mStream.BeginRead(buffer, offset, size, new AsyncCallback(RecvCallback), rh); }
void GetResponseCallback(IAsyncResult asyncResult) { try { WebResponse = WebRequest.EndGetResponse(asyncResult); Stream = WebResponse.GetResponseStream(); BufferOffset = 0; Stream.BeginRead(Buffer, BufferOffset, Buffer.Length, ReadCallback, null); } catch(System.Exception e) { Exception = e; } }
/// <summary> /// Transfers an entire source stream to a target /// </summary> /// <param name="source"> /// The stream to read /// </param> /// <param name="target"> /// The stream to write /// </param> /// <returns> /// The total number of bytes transferred /// </returns> public Int32 Copy(Stream source, Stream target) { var copied = 0; var bufferIdx = 0; // start an initial dummy write to avoid // a null test within the copy loop var writer = target.BeginWrite(this.buffers[1], 0, 0, null, null); for (; ; ) { // read into the current buffer var buffer = this.buffers[bufferIdx]; var reader = source.BeginRead(buffer, 0, buffer.Length, null, null); // complete the previous write and the current read target.EndWrite(writer); var read = source.EndRead(reader); if (read == 0) break; copied += read; // start the next write for the completed read writer = target.BeginWrite(buffer, 0, read, null, null); // swap the buffer index for the next read bufferIdx = (bufferIdx + 1) % 2; } return copied; }
public void Load(SafeUri uri) { if (is_disposed) return; //First, send a thumbnail if we have one if ((thumb = XdgThumbnailSpec.LoadThumbnail (uri, ThumbnailSize.Large, null)) != null) { pixbuf_orientation = ImageOrientation.TopLeft; EventHandler<AreaPreparedEventArgs> prep = AreaPrepared; if (prep != null) prep (this, new AreaPreparedEventArgs (true)); EventHandler<AreaUpdatedEventArgs> upd = AreaUpdated; if (upd != null) upd (this, new AreaUpdatedEventArgs (new Rectangle (0, 0, thumb.Width, thumb.Height))); } using (var image_file = ImageFile.Create (uri)) { image_stream = image_file.PixbufStream (); pixbuf_orientation = image_file.Orientation; } loading = true; // The ThreadPool.QueueUserWorkItem hack is there cause, as the bytes to read are present in the stream, // the Read is CompletedAsynchronously, blocking the mainloop image_stream.BeginRead (buffer, 0, count, delegate (IAsyncResult r) { ThreadPool.QueueUserWorkItem (delegate {HandleReadDone (r);}); }, null); }
private void RunningLoop() { byte[] buffer = new byte[20]; int received = 0; while (running) { while (running) { try { ns.BeginRead(buffer, 0, 20, AsyncReceiveCallback, this); //received = ns.Read(buffer, 0, 20); } catch (Exception e) { //Console.WriteLine(e.ToString()); continue; } if (received > 0) { //System.Diagnostics.Trace.WriteLine(BitConverter.ToString(buffer)); //this.Invoke(setRcvText, BitConverter.ToString(buffer)); if (buffer[0] == 0x01) { string text = System.Text.Encoding.UTF8.GetString(buffer, 2, buffer.Length - 2) + " id:" + buffer[1] + " connected"; this.Invoke(setLabelStatus, new object[] { text, Color.Lime }); } //string command = ""; //Keys keycode = (Keys)BitConverter.ToInt16(buffer, 0); //switch(keycode) //{ // case Keys.Up: // command = "{UP}"; // break; // case Keys.Down: // command = "{DOWN}"; // break; // case Keys.Left: // command = "{LEFT}"; // break; // case Keys.Right: // command = "{RIGHT}"; // break; // case Keys.Enter: // command = "{ENTER}"; // break; //System.Diagnostics.Trace.WriteLine(@"SendWait(""" + command + @""")"); //System.Windows.Forms.SendKeys.SendWait(command); } else { Console.WriteLine("connection lost"); running = false; break; } } try { bc.Close(); Console.WriteLine("closed"); running = false; break; } catch { running = false; break; } } }
public void Read(System.IO.Stream stream) { stream.BeginRead(buffer, 0, buffer.Length, this.DoRead, null); }
void HandleReadDone(IAsyncResult ar) { if (is_disposed) { return; } int byte_read = image_stream.EndRead(ar); lock (sync_handle) { if (byte_read == 0) { image_stream.Close(); Close(); Loading = false; notify_completed = true; } else { try { if (!is_disposed && Write(buffer, (ulong)byte_read)) { image_stream.BeginRead(buffer, 0, count, HandleReadDone, null); } } catch (ObjectDisposedException) { } catch (GLib.GException) { } } } GLib.Idle.Add(delegate { //Send the AreaPrepared event if (notify_prepared) { notify_prepared = false; if (thumb != null) { thumb.Dispose(); thumb = null; } AreaPrepared?.Invoke(this, new AreaPreparedEventArgs(false)); } //Send the AreaUpdated events if (damage != Rectangle.Zero) { AreaUpdated?.Invoke(this, new AreaUpdatedEventArgs(damage)); damage = Rectangle.Zero; } //Send the Completed event if (notify_completed) { notify_completed = false; OnCompleted(); } return(false); }); }
public ReadTransaction(System.IO.Stream s, byte[] dest, int off, int len) : base(true, new System.AsyncCallback((iar) => s.BeginRead(dest, off, len, new System.AsyncCallback((ia) => s.EndRead(ia)), null)), null, null) { }
/// <inheritdoc/> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return(_underlyingStream.BeginRead(buffer, offset, count, callback, state)); }