private void Client_TextReceived(object sender, TextReceivedEventArgs e) { var args = new ServerReceivedTextEventArgs(sender as Connection, e); TextReceived?.Invoke(this, args); OnTextReceived(args); }
private void DataReceive() { while (Tcp?.Connected ?? false) { try { byte message = Reader.ReadByte(); switch (message) { case READY_BYTE: Writer.Write(READY_BYTE); break; case COMMAND_BYTE: byte command = Reader.ReadByte(); byte processNumber = Reader.ReadByte(); CommandReceived?.Invoke(this, new Message <byte>(command, processNumber)); break; case TEXT_BYTE: string text = Reader.ReadString(); processNumber = Reader.ReadByte(); TextReceived?.Invoke(this, new Message <string>(text, processNumber)); break; } } catch { Connected = false; return; } } Connected = false; }
public static void SendText(string text) { if (text == string.Empty) { for (int i = 0; i < height && waiting.Count > 0; i++) { Enqueue(waiting.Dequeue()); } return; } lastTyped.Add(text); typedIndex = lastTyped.Count; if (commands.Any(c => c.IsMatch(text))) { var cmd = commands.FirstOrDefault(c => c.IsMatch(text)); Log(">\t" + text); intend = true; intendation = 2; cmd.Invoke(text); intend = false; } else if (!string.IsNullOrWhiteSpace(text.Trim('/'))) { Error("Typed:"); Error("\t" + text, Color.Red, Color.DarkGray); Error("Couldn't match to any command"); } TextReceived?.Invoke(text); }
private async Task ReceiveMessagesAsync(CancellationToken token) { try { var sb = new StringBuilder(); while (_clientWebSocket.State == WebSocketState.Open) { WebSocketReceiveResult result; _buffer = new ArraySegment <byte>(new byte[BufferSize]); sb.Clear(); do { result = await _clientWebSocket.ReceiveAsync(_buffer, token); var message = Encoding.UTF8.GetString(_buffer.Array, 0, result.Count); sb.Append(message); } while (!result.EndOfMessage); await TextReceived.InvokeAsync(this, sb.ToString()); } } catch (Exception e) { await Closed.InvokeAsync(this, EventArgs.Empty); } }
private void ReceiveText(byte[] bytes) { try { TextReceived?.Invoke(Encoding.ASCII.GetString(bytes)); } catch (Exception ex) { throw ex; } }
void ReadThreadBody() { try { Thread.CurrentThread.Name = "Telnet command readout thread"; if (_CommandLine == null) { //This is a special console that already had an active command when this class received it. Hence we don't wait for the start marker. } else { //Read and discard everything before the start marker. These lines to not belong to our command. _Connection.SetTimeout(1000); string text = _Connection.ReadTextUntilEventAndHandleTelnetCommands(s => s.EndsWith(_BeginMarker + "\r\n")); _Connection.SetTimeout(0); } //We don't know for sure where the command output ends and our end marker starts. Hence we have to guess it and immediately output everything that does not //look like the end marker. This has a bad side effect that all output looking like the beginning of our end marker will be delayed until we are 100% sure that //it's not the actual marker; bool atEndOfLine = true; for (;;) { string output = _Connection.ReadTextUntilEventAndHandleTelnetCommands(s => !atEndOfLine || (!_EndMarker.StartsWith(s) || s == _EndMarker)); if (output == _EndMarker) { string code = _Connection.ReadTextUntilEventAndHandleTelnetCommands(s => s.EndsWith("E")); int parsedCode; if (code.EndsWith("E") && int.TryParse(code.TrimEnd('E'), out parsedCode)) { CommandExited?.Invoke(this, parsedCode); } else { CommandExited?.Invoke(this, null); } _ExitedNormally = true; return; } atEndOfLine = output.EndsWith("\n"); TextReceived?.Invoke(this, output, CommandStreamType.Stdout); } } catch { CommandExited?.Invoke(this, null); } }
public void FileChanged(string path) { var context = _paths.GetOrAdd(path, s => { var c = Context.For(s); Logger.Debug("Session {0}: Started", c.SessionId); return(c); }); if (!File.Exists(path)) { RemoveContext(path); RxMessageBrokerMinimod.Default.Send(new SessionTerminated(context.SessionId)); return; } using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8)) { if (reader.BaseStream.Length == context.Offset) { return; } reader.BaseStream.Seek(context.Offset, SeekOrigin.Begin); var buffer = new char[500000]; int charsRead; while ((charsRead = reader.ReadBlock(buffer, 0, buffer.Length)) > 0) { var text = new TextReceived(context.SessionId, context.Offset, reader.BaseStream.Position, new string(buffer.Take(charsRead).ToArray())); Logger.Debug("Session {0}: Text received, offset {1} to {2}", context.SessionId, context.Offset, reader.BaseStream.Position); RxMessageBrokerMinimod.Default.Send(text); context.Offset = reader.BaseStream.Position; } } }
private void HandleFrame(Frame frame) { if (frame.FIN) { switch (frame.OpCode) { case OpCode.TextFrame: binary.AddRange(frame.UnmaskedData); TextReceived?.Invoke(this, Encoding.UTF8.GetString(binary.ToArray())); break; case OpCode.BinaryFrame: binary.AddRange(frame.UnmaskedData); BinaryReceived?.Invoke(this, binary.ToArray()); break; case OpCode.ConnectionClose: HandleCloseRequest(frame); break; case OpCode.Ping: Pong(frame); break; case OpCode.ContinuationFrame: if (currentOpCode == OpCode.TextFrame) { TextReceived?.Invoke(this, Encoding.UTF8.GetString(binary.ToArray())); } else { BinaryReceived?.Invoke(this, binary.ToArray()); } break; default: Close(); break; } binary.Clear(); } else { binary.AddRange(frame.UnmaskedData); currentOpCode = frame.OpCode; } }
private void HandleFrame(Frame frame) { if (frame.FIN) { switch (frame.OpCode) { case OpCode.TextFrame: var ignore1 = Task.Run(() => TextReceived?.Invoke(this, new TextReceivedEventArgs(Encoding.UTF8.GetString(frame.UnmaskedData)))); break; case OpCode.BinaryFrame: var ignore2 = Task.Run(() => BinaryReceived?.Invoke(this, new BinaryReceivedEventArgs(frame.UnmaskedData))); break; case OpCode.ConnectionClose: HandleCloseRequest(frame); break; case OpCode.Ping: Pong(frame); break; case OpCode.ContinuationFrame: binary.AddRange(frame.UnmaskedData); if (currentOpCode == OpCode.TextFrame) { var ignore3 = Task.Run(() => TextReceived?.Invoke(this, new TextReceivedEventArgs(Encoding.UTF8.GetString(binary.ToArray())))); } else { var ignore4 = Task.Run(() => BinaryReceived?.Invoke(this, new BinaryReceivedEventArgs(binary.ToArray()))); } break; default: Close(); break; } binary.Clear(); } else { binary.AddRange(frame.UnmaskedData); currentOpCode = frame.OpCode; } }
/// <summary> /// 数据接收回调函数 /// </summary> /// <param name="asyncResult"></param> private void HandleTcpClientReceived(IAsyncResult asyncResult) { if (TcpClient.Connected) { int numberOfReadBytes = 0; try { numberOfReadBytes = TcpClient.GetStream().EndRead(asyncResult); } catch { numberOfReadBytes = 0; } if (numberOfReadBytes == 0) { Status = NetStatus.LoseConnected; TcpClient.Close(); TcpClient = new TcpClient(); LoseConnected?.Invoke(this, new EventArgs()); return; } byte[] recvBuffer = new byte[numberOfReadBytes]; Buffer.BlockCopy((byte[])asyncResult.AsyncState, 0, recvBuffer, 0, numberOfReadBytes); if (isWait) { lock (objLock) { bytesForWait = recvBuffer; } } else { DataReceived?.Invoke(this, recvBuffer); string text = this.ClientEncoding.GetString(recvBuffer); TextReceived?.Invoke(this, text); } byte[] readBuffer = new byte[this.TcpClient.ReceiveBufferSize]; TcpClient.GetStream().BeginRead(readBuffer, 0, readBuffer.Length, new AsyncCallback(HandleTcpClientReceived), readBuffer); //lock (lockobj) //{ // System.IO.File.AppendAllText(Application.StartupPath + "\\log.txt", string.Format("{0:DD-mm-ss}<=={1}\r\n", DateTime.Now, Encoding.Default.GetString(recvBuffer))); //} } }
void Send(TextReceived output) { Logger.Info("Session {0}: Sending, offset {1} to {2}: {3}", output.SessionId, output.StartOffset, output.EndOffset, Pad(output.Text, 10)); try { _hub.Invoke <string>("Broadcast", _groupId, output).Wait(); } catch (Exception exception) { Logger.Error(MaybeAggregateException(exception), $"Session {output.SessionId}: Error sending request"); throw; } }
private void sendToForm() { String [] infoBox = { "", "Val3 Ver", "Arm Type", "Tuning", "Mounting", "Controller SN", "Arm SN", "Starc" }; string[] messages = TextReceived.Split(','); ListBox lstBox = wForm.getInfBox(); int j = 1; if (TextToSend == "INF") { foreach (var msg in messages) { lstBox.Items.Add(infoBox[j] + ": " + msg); j++; } } else if (TextToSend == "LP1") { lstBox.Items.Add("Time: " + TextReceived); } }
async Task Send(TextReceived textReceived) { string Prefix(string text, int length) { if (text.Length >= length) { return(string.Concat(text.AsSpan(0, length - 1), "...")); } return(text); } _logger.LogInformation("Session {SessionId}: Sending, offset {StartOffset} to {EndOffset}: {Text}", textReceived.SessionId, textReceived.StartOffset, textReceived.EndOffset, Prefix(textReceived.Text, 10)); await _connection.Hub.InvokeAsync <string>("Broadcast", _groupOptions.Id, textReceived); }
private void ReceiveCallback(IAsyncResult ar) { Socket current = (Socket)ar.AsyncState; int received; try { received = current.EndReceive(ar); } catch (SocketException) { // Console.WriteLine("Client forcefully disconnected"); ClientForcefullyDisconnected?.Invoke(); // Don't shutdown because the socket may be disposed and its disconnected anyway. current.Close(); ClientSockets.Remove(current); return; } byte[] recBuf = new byte[received]; Array.Copy(Buffer, recBuf, received); string text = Encoding.ASCII.GetString(recBuf); // Console.WriteLine("Received Text: " + text); if (text.ToLower() == "") { ClientDisconnected?.Invoke(); return; } else { byte[] data = Encoding.ASCII.GetBytes("Received"); current.Send(data); TextReceived?.Invoke(text); } current.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, current); }
/// <inheritdoc /> public void OnTextReceived(TextReceivedEventArg e) { TextReceived?.Invoke(e); }
public void Broadcast(string groupId, TextReceived text) { GroupForInstance(groupId).SendAsync("text", text); }
private async void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { Stream streamIn = args.GetDataStream().AsStreamForRead(); HostName serverAddressFull; using (var reader = new StreamReader(streamIn)) { serverName = await reader.ReadToEndAsync(); serverAddressFull = args.RemoteAddress; serverAddress = serverAddressFull.ToString(); LoggingManager.Log("Detected " + serverName + " (" + serverAddress + "), attempting to establish tcp connection"); } commandSocket = new StreamSocket(); await commandSocket.ConnectAsync(serverAddressFull, commandPort.ToString()); LoggingManager.Log("Tcp connection established, sending handshake"); var commandStreamOut = commandSocket.OutputStream.AsStreamForWrite(); commandOut = new StreamWriter(commandStreamOut, Encoding.UTF8); commandOut.WriteLine(deviceName); commandOut.Flush(); LoggingManager.Log("Handshake sent, establishing video connection"); videoSocket = new StreamSocket(); await videoSocket.ConnectAsync(serverAddressFull, videoPort.ToString()); Connected?.Invoke(); connected = true; LoggingManager.Log("Video connection established, starting new threads"); _ = Task.Run(async() => { try { var commandStreamIn = commandSocket.InputStream.AsStreamForRead(); var reader = new StreamReader(commandStreamIn, Encoding.UTF8); while (true) { string message = await reader.ReadLineAsync(); if (message.Length > 0) { TextReceived?.Invoke(message); //LoggingManager.Log("Received message: " + message); } } } catch { LostConnection?.Invoke(); connected = false; } }); _ = Task.Run(async() => { try { var videoStreamIn = new DataReader(videoSocket.InputStream); videoStreamIn.ByteOrder = ByteOrder.LittleEndian; // need to set this or the bytes will be read in the wrong order videoOut = new DataWriter(videoSocket.OutputStream); videoOut.ByteOrder = ByteOrder.LittleEndian; //byte[] buffer = new byte[640 * 640 * 3]; // load the bytes for the first integer, the image size var count = await videoStreamIn.LoadAsync(4); while (true) { int length = videoStreamIn.ReadInt32(); // first read the image size (in # of bytes) //Debug.Log("Attempting to read image of length " + length); // read the image byte[] buffer = new byte[length]; count = await videoStreamIn.LoadAsync((uint)length); videoStreamIn.ReadBytes(buffer); //ImageReceived?.Invoke(buffer); // convert the bytes to a stream var imgStream = buffer.AsBuffer().AsStream().AsRandomAccessStream(); //Debug.Log("Read image, decoding"); // decode the image var decoder = await BitmapDecoder.CreateAsync(imgStream); imgStream.Seek(0); int width = (int)decoder.PixelWidth; int height = (int)decoder.PixelHeight; var data = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); var decodedBytes = data.DetachPixelData(); // display the image ImageReceived?.Invoke(decodedBytes, width, height); //Debug.Log("Received image"); // clean up memory buffer = null; data = null; decodedBytes = null; GC.GetTotalMemory(true); // start to read the next image count = await videoStreamIn.LoadAsync(4); } } catch { LostConnection?.Invoke(); connected = false; } }); }
private void Server_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { if (sender == commandSocket) { LoggingManager.Log("Command connection received"); Connected?.Invoke(); _ = Task.Run(async() => { try { var commandStreamIn = args.Socket.InputStream.AsStreamForRead(); var reader = new StreamReader(commandStreamIn, Encoding.UTF8); var commandStreamOut = args.Socket.OutputStream.AsStreamForWrite(); commandOut = new StreamWriter(commandStreamOut, Encoding.UTF8); while (true) { string message = await reader.ReadLineAsync(); if (message.Length > 0) { TextReceived?.Invoke(message); //LoggingManager.Log("Received message: " + message); } } } catch { LostConnection?.Invoke(); connected = false; } }); } else if (sender == videoSocket) { LoggingManager.Log("Video connection received"); _ = Task.Run(async() => { try { var videoStreamIn = new DataReader(args.Socket.InputStream); videoStreamIn.ByteOrder = ByteOrder.LittleEndian; // need to set this or the bytes will be read in the wrong order // load the bytes for the first five integers (4 bytes each), the image size and four values for the time (h, m, s, ms) var count = await videoStreamIn.LoadAsync(20); double avgLag = 0, avgLagCount = 0; double avgFps = 0, frameCount = 0; Queue <Tuple <DateTime, double> > fpsQueue = new Queue <Tuple <DateTime, double> >(); double prevFps = 0; double minFps = 0; while (true) { int length = videoStreamIn.ReadInt32(); // first read the image size (in # of bytes) int h = videoStreamIn.ReadInt32(); // hours int m = videoStreamIn.ReadInt32(); // minutes int s = videoStreamIn.ReadInt32(); // seconds int ms = videoStreamIn.ReadInt32(); // milliseconds DateTime timeReceived = DateTime.Now; DateTime timeSent = new DateTime(timeReceived.Year, timeReceived.Month, timeReceived.Day, h, m, s, ms); double elapsed = (timeReceived - timeSent).TotalMilliseconds; //LoggingManager.Log("Frame Lag: " + elapsed.ToString("0") + " ms"); // average the first several frames to measure base lag if (avgLagCount < 10) { avgLag += elapsed / 10; avgLagCount++; } //LoggingManager.Log("Attempting to read image of length " + length); // read the image DateTime start = DateTime.Now; byte[] buffer = new byte[length]; count = await videoStreamIn.LoadAsync((uint)length); videoStreamIn.ReadBytes(buffer); //ImageReceived?.Invoke(buffer); //ImageDecoded?.Invoke(buffer, 720, 1280); // Fixes lag getting worse over time, but causes image freezing issue //if(videoStreamIn.UnconsumedBufferLength > 0 || (elapsed > avgLag + 200)) //{ // LoggingManager.Log("Frame Dropped (" + (elapsed > avgLag + 200 ? "excess lag" : "next frame ready") + ")"); // // clean up used memory // buffer = null; // GC.GetTotalMemory(true); // // start to read the next image // count = await videoStreamIn.LoadAsync(20); // // skip to next frame without procesing the current one // continue; //} // send confirmation that we received this frame along with the minimum fps over the past couple of seconds (rounded down to prevent lag) if (commandOut != null) { int fps = (int)Math.Ceiling(minFps - 1); if (fps != prevSentFps) { LoggingManager.Log("Set FPS: " + fps); prevSentFps = fps; } string confirmationString = string.Format("{0},{1},{2},{3},{4}\n", h, m, s, ms, fps); commandOut.Write(confirmationString); commandOut.Flush(); //Debug.Log(confirmationString); } //LoggingManager.Log("Read Image: " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0")); //start = DateTime.Now; // convert the bytes to a stream var imgStream = buffer.AsBuffer().AsStream().AsRandomAccessStream(); //LoggingManager.Log("Read image, decoding"); // decode the image var decoder = await BitmapDecoder.CreateAsync(imgStream); imgStream.Seek(0); int width = (int)decoder.PixelWidth; int height = (int)decoder.PixelHeight; //LoggingManager.Log("Create Decoder: " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0")); //start = DateTime.Now; var data = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); //LoggingManager.Log("Get Pixel Data: " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0")); //start = DateTime.Now; var decodedBytes = data.DetachPixelData(); //LoggingManager.Log("Detach Pixel Data: " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0")); //start = DateTime.Now; //LoggingManager.Log("Decode Image: " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0")); //start = DateTime.Now; // display the image ImageDecoded?.Invoke(decodedBytes, width, height); //LoggingManager.Log("Received image (" + width + " x " + height + "), " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0") + "ms"); //LoggingManager.Log("Received Image: " + (DateTime.Now - start).TotalMilliseconds.ToString("0.0")); // clean up memory buffer = null; data = null; decodedBytes = null; GC.GetTotalMemory(true); // update fps double currFps = 1.0 / (DateTime.Now - start).TotalSeconds; if (frameCount > 0) { avgFps *= frameCount; } avgFps += currFps; frameCount++; avgFps /= frameCount; prevFps = currFps; fpsQueue.Enqueue(new Tuple <DateTime, double>(DateTime.Now, currFps)); while (fpsQueue.Count > 20 || (DateTime.Now - fpsQueue.Peek().Item1).TotalSeconds > 2) { fpsQueue.Dequeue(); } minFps = double.MaxValue; foreach (var val in fpsQueue) { if (val.Item2 < minFps) { minFps = val.Item2; } } // start to read the next image count = await videoStreamIn.LoadAsync(20); } } catch { LostConnection?.Invoke(); connected = false; } }); } }
private void cleanMsg() { TextReceived = TextReceived.Replace("?", ""); }
private void ProcessTerminalCode(TerminalCode code, TerminalCode lastCode) { switch (code.Type) { case TerminalCodeType.ResetMode: Buffer.ShowCursor = false; break; case TerminalCodeType.SetMode: Buffer.ShowCursor = true; // HACK We want clear to reset the window position but not general typing. // We therefore reset the window only if the cursor is moved to the top. if (Buffer.CursorY == 0) { Buffer.WindowTop = 0; } break; case TerminalCodeType.Text: Buffer.Type(code.Text); _nextTextEventArgs.Text += code.Text; break; case TerminalCodeType.LineFeed: if (lastCode.Type != TerminalCodeType.CarriageReturn) { TextReceived?.Invoke(this, _nextTextEventArgs); _nextTextEventArgs = new TextEventArgs(); if (ImplicitCrForLf) { ProcessTerminalCode(TerminalCode.EraseLine, TerminalCode.Dummy); ProcessTerminalCode(TerminalCode.Cr, TerminalCode.Dummy); } } if (Buffer.CursorY == Buffer.Size.Rows - 1) { Buffer.ShiftUp(); } else { Buffer.CursorY++; } break; case TerminalCodeType.CarriageReturn: TextReceived?.Invoke(this, _nextTextEventArgs); _nextTextEventArgs = new TextEventArgs(); Buffer.CursorX = 0; break; case TerminalCodeType.CharAttributes: Buffer.CurrentCharAttributes = code.CharAttributes; break; case TerminalCodeType.CursorPosition: Buffer.CursorX = code.Column; Buffer.CursorY = code.Line; break; case TerminalCodeType.CursorUp: Buffer.CursorY -= code.Line; break; case TerminalCodeType.CursorCharAbsolute: Buffer.CursorX = code.Column; break; case TerminalCodeType.EraseInLine: if (code.Line == 0) { Buffer.ClearBlock(Buffer.CursorX, Buffer.CursorY, Buffer.Size.Columns - 1, Buffer.CursorY); } break; case TerminalCodeType.EraseInDisplay: Buffer.Clear(); Buffer.CursorX = 0; Buffer.CursorY = 0; break; case TerminalCodeType.SetTitle: Title = code.Text; TitleChanged?.Invoke(this, EventArgs.Empty); break; } }
protected virtual void OnTextReceived(TextReceivedEventArgs e) { TextReceived.Invoke(this, e); }