1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using System;
- using System.Diagnostics;
- using System.Threading.Tasks;
- namespace WebTerminalServer
- {
- public class EasyTerminal
- {
- private readonly string _cmdExe;
- private Process _process;
- public EasyTerminal(string cmdExe)
- {
- _cmdExe = cmdExe;
- }
- public EventHandler<byte[]> DataReceived { get; set; }
- public EventHandler<uint> CloseReceived { get; set; }
- public void OnInput(byte[] ee)
- {
- if (ee == null) throw new ArgumentException();
- if (ee.Length == 1 && ee[0] == 13)
- {
- _process.StandardInput.WriteLine();
- _process.StandardInput.Flush();
- _process.StandardInput.BaseStream.Flush();
- return;
- }
- _process.StandardInput.BaseStream.Write(ee, 0, ee.Length);
- _process.StandardInput.BaseStream.Flush();
- }
- public void OnClose()
- {
- _process?.Kill();
- }
- public void Run()
- {
- _process = new Process
- {
- StartInfo =
- {
- FileName = _cmdExe,
- RedirectStandardError = true,
- RedirectStandardInput = true,
- RedirectStandardOutput = true,
- UseShellExecute = false
- },
- EnableRaisingEvents = true
- };
- _process.Exited += delegate { CloseReceived?.Invoke(this, (uint)_process.ExitCode); };
- _process.Start();
- Task.Run(async delegate
- {
- var s = _process.StandardOutput.BaseStream;
- var buf = new byte[1024];
- while (_process.HasExited == false)
- {
- var count = await s.ReadAsync(buf, 0, buf.Length);
- var outBuf = new byte[count];
- Buffer.BlockCopy(buf, 0, outBuf, 0, count);
- DataReceived?.Invoke(this, outBuf);
- }
- });
- Task.Run(async delegate
- {
- var s = _process.StandardError.BaseStream;
- var buf = new byte[1024];
- while (_process.HasExited == false)
- {
- var count = await s.ReadAsync(buf, 0, buf.Length);
- var outBuf = new byte[count];
- Buffer.BlockCopy(buf, 0, outBuf, 0, count);
- DataReceived?.Invoke(this, outBuf);
- }
- });
- }
- }
- }
|