-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAppServer.cs
More file actions
83 lines (68 loc) · 2.76 KB
/
AppServer.cs
File metadata and controls
83 lines (68 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
namespace TelnetClientServer;
public class AppServer
{
private const string LogPrefix = $"[ {nameof(AppServer)} ]";
private readonly TcpListener _tcpListener;
private readonly ProcessStartInfo _processStartInfo;
public AppServer(string executable, int port)
{
_tcpListener = new TcpListener(IPAddress.Any, port);
_processStartInfo = new ProcessStartInfo(executable)
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
Console.WriteLine($"{LogPrefix} Created. Executable \"{executable}\" to port {port}.");
}
private Process? StartProcess()
{
try
{
var process = Process.Start(_processStartInfo);
if (process != null)
{
return process;
}
Console.WriteLine($"{LogPrefix} Process cannot be started.");
}
catch (Exception exception)
{
Console.WriteLine($"{LogPrefix} Error when start the process: {exception.Message}");
}
return null;
}
public void Start()
{
Console.WriteLine($"{LogPrefix} Starting. Press ESC to exit.");
_tcpListener.Start();
while (!Console.KeyAvailable || Console.ReadKey(true).Key != ConsoleKey.Escape)
{
if (_tcpListener.Pending())
{
Console.WriteLine($"{LogPrefix} Connection received.");
var tcpClient = _tcpListener.AcceptTcpClient();
var process = StartProcess();
if (process != null)
{
Console.WriteLine($"{LogPrefix} Process executed: {process.StartInfo.FileName}");
new PipeStream(tcpClient.GetStream(), process.StandardInput.BaseStream, nameof(tcpClient), nameof(process.StandardInput)).BeginRead();
new PipeStream(process.StandardOutput.BaseStream, tcpClient.GetStream(), nameof(process.StandardOutput), nameof(tcpClient)).BeginRead();
new PipeStream(process.StandardError.BaseStream, tcpClient.GetStream(), nameof(process.StandardError), nameof(tcpClient)).BeginRead();
Console.WriteLine($"{LogPrefix} Pipe of stream was configured.");
}
else
{
Console.WriteLine($"{LogPrefix} Closing.");
tcpClient.Close();
}
}
Thread.Sleep(1);
}
Console.WriteLine($"{LogPrefix} Terminated.");
}
}