public async Task HandleLines() { try { var strm = _tcpClient.GetStream(); using (StreamReader reader = new StreamReader(strm, Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { LineReceived?.Invoke(this, line); } } } catch (IOException ex) { Log?.Error("HandleLines::IOException", ex); } catch (InvalidOperationException ex) { Log?.Error("HandleLines::InvalidOperationException", ex); } await Task.Delay(1000); }
public async Task HandleLines() { try { var strm = NativeClient.GetStream(); using var reader = new StreamReader(strm, Encoding.UTF8); string line; while ((line = await reader.ReadLineAsync()) != null) { LineReceived?.Invoke(this, line); } } catch (IOException ex) { //Logger?.Log?.Error("HandleLines::IOException", ex); Failed?.Invoke(this, new MessageEventArgs(ex.Message)); } catch (InvalidOperationException ex) { Logger?.Log?.Error("HandleLines::InvalidOperationException", ex); Failed?.Invoke(this, new MessageEventArgs(ex.Message)); } Disconnected?.Invoke(this, null !); await Task.Delay(1000); }
public virtual void OnLineReceived(string e) { if (e == string.Empty) { return; } LineReceived?.Invoke(this, e); }
private void receiveLoop() { while (serialPort.IsOpen) { string line; try { line = serialPort.ReadLine(); } catch (TimeoutException) { continue; } catch (Exception e) { Debug.WriteLine(e); serialPort.Close(); break; } #if LOG_TRAFFIC_CONSOLE Console.WriteLine("RECV: " + line); #endif line = line.Trim(); if (line == "ok") { completeQueuedRequest(GrblResponseStatus.Ok); } else if (line.StartsWith("<")) { completeStatusQueryRequest(GrblResponseStatus.Ok); } else if (line.StartsWith("error:")) { int errorCode; int.TryParse(line.Substring(6), out errorCode); completeQueuedRequest(GrblResponseStatus.Error, errorCode); } else if (line.StartsWith("Grbl ")) { completeAll(GrblResponseStatus.Failure); if (!line.StartsWith("Grbl 1.1")) { UnsupportedVersion?.Invoke(this, line); } } LineReceived?.Invoke(this, line); } completeAll(GrblResponseStatus.Failure); Closed?.Invoke(this); }
private void Run() { Connected = true; while (Connected) { string line = _reader.ReadLine(); if (line == null) { Connected = false; return; } LineReceived?.Invoke(line); } }
public void HandleReceive() { while (_outgoingLines.TryDequeue(out var line)) { this._connection.WriteLine(line); LineSent?.Invoke(this, new LineEventArgs(Line.Parse(line))); } var selectableSockets = new List <Socket>() { _connection.Socket }; Socket.Select(selectableSockets, null, null, 1000); if (selectableSockets.Count == 0) { return; } var linesReceived = _connection.HandleReceive(); foreach (var line in linesReceived) { if (line.Command == "PING") // Automatically respond to ping { this._connection.WriteLine($"PONG :{line.Params[0]}"); } // Gross and basic parsing, for demonstration purposes. Message.Type type = line.Command switch { "372" => Message.Type.Motd, "376" => Message.Type.EndOfMotd, "PRIVMSG" => "#&".IndexOf(line.Params[0][0]) != -1 ? Message.Type.ChannelMessage : Message.Type.PrivateMessage, "PING" => Message.Type.Ping, "JOIN" => Message.Type.Join, "PART" => Message.Type.Part, "NOTICE" => Message.Type.Notice, _ => Message.Type.Raw }; MessageReceived?.Invoke(this, new MessageEventArgs(new Message(line, type))); LineReceived?.Invoke(this, new LineEventArgs(line)); } }
private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { var serialPort = sender as SerialPort; var bytes = new byte[serialPort.BytesToRead]; serialPort.Read(bytes, 0, bytes.Length); _LineBuff += Encoding.ASCII.GetString(bytes); var n = default(int); while ((n = _LineBuff.IndexOf('\n')) != -1) { var line = _LineBuff.Substring(0, n).TrimEnd('\r'); _LineBuff = _LineBuff.Substring(n + 1); LineReceived?.Invoke(serialPort, new SerialLineReceivedEventArgs(line)); } }
public void AddData(byte[] buffer) { int offset = 0; while (true) { int newlineIndex = Array.IndexOf(buffer, Delimiter, offset); if (newlineIndex < offset) { current = ConcatArray(current, buffer, offset, buffer.Length - offset); return; } ++newlineIndex; byte[] full_line = ConcatArray(current, buffer, offset, newlineIndex - offset); current = null; offset = newlineIndex; LineReceived?.Invoke(full_line); } }
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (port == null || !port.IsOpen) { return; } int available = port.BytesToRead; byte[] data = new byte[available]; port.Read(data, 0, available); incomingData.AddRange(Encoding.ASCII.GetChars(data)); while (incomingData.Contains('\r')) { int index = incomingData.IndexOf('\r'); string line = new string(incomingData.GetRange(0, index + 1).ToArray()).Replace("\n", "").Replace('\r', '\n'); incomingData.RemoveRange(0, index + 1); LineReceived?.Invoke(line); } }
public void OnIncomingBinaryBlock(byte[] buffer) { // Debug.Log("OnIncomingBinaryBlock " + buffer.Length.ToString()); int offset = 0; while (true) { int newlineIndex = Array.IndexOf(buffer, Delimiter, offset); if (newlineIndex < offset) { leftover = ConcatArray(leftover, buffer, offset, buffer.Length - offset); break; } ++newlineIndex; byte[] full_line = ConcatArray(leftover, buffer, offset, newlineIndex - offset); leftover = null; offset = newlineIndex; LineReceived?.Invoke(full_line); // raise an event for further processing } }
private void OnDataReceived(object sender, SerialDataReceivedEventArgs e) { while (_port.BytesToRead > 0) { if (_receivingCanMsg) { ReadCanMessage(); } else { // Reads a byte and detect packet type var b = (byte)_port.ReadByte(); switch (b) { case 0x03: // CAN message ReadCanMessage(); break; case 0x7B: // Json message ('{') ReadJsonString(); break; case 0xFF: // OK message (COMMAND_OK) // Discard two next bytes (line terminator) _port.ReadByte(); _port.ReadByte(); OkReceived?.Invoke(true); break; case 0x80: // Error message (COMMAND_ERROR) OkReceived?.Invoke(false); break; default: // Reads a line var line = ((char)b) + _port.ReadLine(); LineReceived?.Invoke(line); break; } } } }
private void Receive(IAsyncResult iaAsyncResult) { try { int byteRead; lock (Client.GetStream()) { byteRead = Client.GetStream().EndRead(iaAsyncResult); } LineReceived?.Invoke(this, Encoding.UTF8.GetString(Buffer, 0, byteRead - 1)); lock (Client.GetStream()) { Client.GetStream().BeginRead(Buffer, 0, _bufferSize, Receive, null); } } catch { //ignored } }
void raiseAppSerialDataEvent(byte[] buffer) { int offset = 0; while (true) { int newlineIndex = Array.IndexOf(buffer, Delimiter, offset); if (newlineIndex < offset) { leftover = ConcatArray(leftover, buffer, offset, buffer.Length - offset); return; } ++newlineIndex; byte[] full_line = ConcatArray(leftover, buffer, offset, newlineIndex - offset); leftover = null; offset = newlineIndex; LineReceived?.Invoke(full_line); // raise an event for further processing } }
public void OnIncomingBinaryBlock(byte[] buffer) { int offset = 0; while (true) { int newlineIndex = Array.IndexOf(buffer, Delimiter, offset); if (newlineIndex < offset) { leftover = ConcatArray(leftover, buffer, offset, buffer.Length - offset); return; } ++newlineIndex; byte[] full_line = ConcatArray(leftover, buffer, offset, newlineIndex - offset); leftover = null; offset = newlineIndex; // Raise an event for further processing. LineReceived?.Invoke(full_line); } }
protected void ReadLines() { string data = string.Empty; while (true) { CancellationToken.Token.ThrowIfCancellationRequested(); uint bytesRead = _serialDataReader.LoadAsync(1024).AsTask(CancellationToken.Token).Result; if (bytesRead > 0) { byte[] buffer = new byte[bytesRead]; _serialDataReader.ReadBytes(buffer); string newData = Encoding.ASCII.GetString(buffer); data = string.Join(data, newData); int newLinePos = data.IndexOf('\n'); while (newLinePos >= 0) { CancellationToken.Token.ThrowIfCancellationRequested(); if (newLinePos > 0) { LineReceived?.Invoke(this, new LineReceivedArgs(data.Substring(0, newLinePos))); } if (newLinePos >= 0) { if (data.Length > newLinePos + 1) { data = data.Substring(newLinePos + 1); } else { data = string.Empty; } } newLinePos = data.IndexOf('\n'); } } } }
private void ProcessMessage(string message) { Console.WriteLine(message); LineReceived?.Invoke(null, message); #if !DEBUG try { using (FileStream fileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileSystemRights.AppendData, FileShare.Write, 4096, FileOptions.None)) { using (StreamWriter streamWriter = new StreamWriter(fileStream)) { streamWriter.AutoFlush = true; streamWriter.WriteLine(message); } } } catch (Exception) { } #endif }
public static void WriteLine(string message) { var line = string.Format("[{0:yyyy-MM-dd HH:mm:ss}] {1}", DateTimeOffset.Now.ToUniversalTime(), message); Console.WriteLine(line); LineReceived?.Invoke(null, new GenericEventArgs <string>(line)); bool isDesignInstance = LicenseManager.UsageMode == LicenseUsageMode.Designtime; if (!isDesignInstance) { try { using var fileStream = new FileStream(s_FileName, FileMode.OpenOrCreate, FileSystemRights.AppendData, FileShare.Write, 4096, FileOptions.None); using var streamWriter = new StreamWriter(fileStream); streamWriter.AutoFlush = true; streamWriter.WriteLine(line); } catch (Exception) { } } }
public void StartHandler(string ip, int port = 15471) { LineReceived += (sender, line) => { if (string.IsNullOrEmpty(line)) { return; } C.WriteLine($"<Empfangen> {line}"); Log("<Recv> {0}", line.Trim()); }; SendFailed += (sender, ex) => C.WriteLine($"<Fehler> {ex.Message}"); Connect(ip, port); var strm = _client.GetStream(); using (var reader = new StreamReader(strm, Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { LineReceived?.Invoke(this, line); } } }
private void ThreadReaderProc() { try { while (true) { int b = _port.ReadByte(); if (b != -1) { RawByteReceived?.Invoke(this, (byte)b); if (b == 0x0d) { _0dRecv = true; } else if (b == 0x0a) { if (_0dRecv) { // строка var s = GetStringFromBuffer(); RawLineReceived?.Invoke(this, s); LineReceived?.Invoke(this, new LineReceivedEventArgs() { Line = s, Type = LineReceivedEventArgs.LineType.General }); _0dRecv = false; _buffer.Clear(); } } else { _buffer.Add((byte)b); if (_buffer.Count == 2 && _buffer[0] == 0x3e && _buffer[1] == 0x20) { // приглашение > LineReceived?.Invoke(this, new LineReceivedEventArgs() { Line = "> ", Type = LineReceivedEventArgs.LineType.Ask }); _0dRecv = false; _buffer.Clear(); } else if (_buffer.Count == 3 && _buffer[0] == 0x3e && _buffer[1] == 0x3e && _buffer[2] == 0x20) { // приглашение >> LineReceived?.Invoke(this, new LineReceivedEventArgs() { Line = ">> ", Type = LineReceivedEventArgs.LineType.DoubleAsk }); _0dRecv = false; _buffer.Clear(); } } } } } catch //(Exception ex) { //... } finally { try { _port.Dispose(); } catch { } } }
protected void NotifyLineReceived() { LineReceived?.Invoke(this, GetLineBufferContents()); ResetLine(); LexerState = 0; }
/// <summary> /// Receiver I got from P21 in the socket pdf /// </summary> private void Receive() { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); byte[] buff = new byte[2048]; do { float stackFrames = 0; try { int count = Socket.Receive(buff); BytesReceived += count; if (count == 0) { Socket.Close(); return; } long position = memoryStream.Position; memoryStream.Seek(0, SeekOrigin.End); memoryStream.Write(buff, 0, count); memoryStream.Position = position; do { long startPosition = memoryStream.Position; try { object thing = binaryFormatter.Deserialize(memoryStream); if (thing is LineSegment) { LineReceived.Invoke(thing); stackFrames++; FramesReceived++; } else { Socket.Close(); return; } } catch (Exception erro) { if (erro is SerializationException) { memoryStream.Position = startPosition; Fragmentation++; break; } else { throw erro; } } } while (memoryStream.Position < memoryStream.Length); if (memoryStream.Position == memoryStream.Length) { memoryStream.Position = 0; memoryStream.SetLength(0); } } catch (Exception erro) { Console.WriteLine($"Client {Address} disconnected"); break; } m_samples++; Destacked = Destacked + (stackFrames - Destacked) / m_samples; } while (Socket.Connected); }
public void OnLineReceived(string message) { LineReceived?.Invoke(this, message); }
protected void FireLineReceived(string line) { LineReceived?.Invoke(this, line); }
public FctbConsoleControl() { InitializeComponent(); fctb.LineReceived += (s, e) => LineReceived?.Invoke(s, e); }
private void InnerLineReceived(string line) { Console.WriteLine("<- " + line); LineReceived?.Invoke(line); }