EasyTerminal.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading.Tasks;
  4. namespace WebTerminalServer
  5. {
  6. public class EasyTerminal
  7. {
  8. private readonly string _cmdExe;
  9. private Process _process;
  10. public EasyTerminal(string cmdExe)
  11. {
  12. _cmdExe = cmdExe;
  13. }
  14. public EventHandler<byte[]> DataReceived { get; set; }
  15. public EventHandler<uint> CloseReceived { get; set; }
  16. public void OnInput(byte[] ee)
  17. {
  18. if (ee == null) throw new ArgumentException();
  19. if (ee.Length == 1 && ee[0] == 13)
  20. {
  21. _process.StandardInput.WriteLine();
  22. _process.StandardInput.Flush();
  23. _process.StandardInput.BaseStream.Flush();
  24. return;
  25. }
  26. _process.StandardInput.BaseStream.Write(ee, 0, ee.Length);
  27. _process.StandardInput.BaseStream.Flush();
  28. }
  29. public void OnClose()
  30. {
  31. _process?.Kill();
  32. }
  33. public void Run()
  34. {
  35. _process = new Process
  36. {
  37. StartInfo =
  38. {
  39. FileName = _cmdExe,
  40. RedirectStandardError = true,
  41. RedirectStandardInput = true,
  42. RedirectStandardOutput = true,
  43. UseShellExecute = false
  44. },
  45. EnableRaisingEvents = true
  46. };
  47. _process.Exited += delegate { CloseReceived?.Invoke(this, (uint)_process.ExitCode); };
  48. _process.Start();
  49. Task.Run(async delegate
  50. {
  51. var s = _process.StandardOutput.BaseStream;
  52. var buf = new byte[1024];
  53. while (_process.HasExited == false)
  54. {
  55. var count = await s.ReadAsync(buf, 0, buf.Length);
  56. var outBuf = new byte[count];
  57. Buffer.BlockCopy(buf, 0, outBuf, 0, count);
  58. DataReceived?.Invoke(this, outBuf);
  59. }
  60. });
  61. Task.Run(async delegate
  62. {
  63. var s = _process.StandardError.BaseStream;
  64. var buf = new byte[1024];
  65. while (_process.HasExited == false)
  66. {
  67. var count = await s.ReadAsync(buf, 0, buf.Length);
  68. var outBuf = new byte[count];
  69. Buffer.BlockCopy(buf, 0, outBuf, 0, count);
  70. DataReceived?.Invoke(this, outBuf);
  71. }
  72. });
  73. }
  74. }
  75. }