-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPipeServer.cs
More file actions
230 lines (185 loc) · 6.16 KB
/
PipeServer.cs
File metadata and controls
230 lines (185 loc) · 6.16 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
using System.Collections.Concurrent;
using System.IO.Pipes;
using System.Text;
namespace AfterburnerViewerServerWin
{
public class PipeServer : IDisposable
{
public string PipeName { get; }
public event EventHandler? OnServerStarted;
public event EventHandler? OnServerStopped;
public event EventHandler? OnNewClient;
public event EventHandler? OnClientDisconnected;
public event EventHandler<string>? OnMessageSend;
private volatile bool isRunning;
private volatile bool isWaitingForClients;
private string? message = null;
private readonly object _lock_msg = new();
protected volatile Thread? runningThread;
protected readonly ConcurrentBag<Thread> clientThreads = [];
protected readonly EventWaitHandle terminateHandle = new(false, EventResetMode.AutoReset);
protected bool disposedValue;
public PipeServer(string pipeName)
{
if (string.IsNullOrWhiteSpace(pipeName))
throw new ArgumentException($"'{nameof(pipeName)}' cannot be null or whitespace.", nameof(pipeName));
PipeName = pipeName;
}
public void Start()
{
if (isRunning || runningThread != null) return;
runningThread = new Thread(ServerLoop);
runningThread.Start();
}
public void Stop()
{
isRunning = false;
clearClientEvents();
breakWaitForConnection();
terminateHandle.WaitOne(1000);
runningThread?.Join(1000);
runningThread = null;
foreach (var clientThread in clientThreads)
{
clientThread.Join(1000);
}
clientThreads.Clear();
OnServerStopped?.Invoke(this, EventArgs.Empty);
}
private void breakWaitForConnection()
{
if (isWaitingForClients)
{
// break blocking WaitForConnection
using NamedPipeClientStream dummy = new(PipeName);
dummy.Connect(100);
}
}
public void WriteToAllClients(string msg)
{
if (string.IsNullOrEmpty(msg)) return;
lock (_lock_msg)
{
message = msg;
}
}
protected void ServerLoop()
{
try
{
OnServerStarted?.Invoke(this, EventArgs.Empty);
terminateHandle.Reset();
isRunning = true;
while (isRunning)
{
var clientPipe = waitForNextClient();
if (clientPipe != null)
handleClientOnNewThread(clientPipe);
}
} finally {
isRunning = false;
terminateHandle.Set();
}
}
protected NamedPipeServerStream? waitForNextClient()
{
try
{
isWaitingForClients = true;
NamedPipeServerStream pipeStream = new(PipeName, PipeDirection.InOut, 254);
pipeStream.WaitForConnection(); // this blocks, we have to break it on dispose
return pipeStream;
}
catch (Exception)
{
//If there are no more avail connections (254 is in use already) then just keep looping until one is avail
return null;
}
finally
{
isWaitingForClients = false;
}
}
protected void handleClientOnNewThread(NamedPipeServerStream pipeStream)
{
// Spawn a new thread for each request and continue waiting
var t = new Thread(clientThread);
t.Start(pipeStream);
clientThreads.Add(t);
}
protected void clientThread(object? o)
{
var clientPipe = (NamedPipeServerStream)o!;
OnNewClient?.Invoke(this, EventArgs.Empty);
try
{
while (isRunning && clientPipe.IsConnected)
{
Thread.Sleep(300);
var msg = popMessageToSend();
if (string.IsNullOrEmpty(msg))
continue;
writeToClient(clientPipe, msg);
OnMessageSend?.Invoke(this, msg);
}
}
catch (Exception)
{
}
finally
{
if (clientPipe.IsConnected)
clientPipe.Disconnect();
clientPipe.Close();
clientPipe.Dispose();
OnClientDisconnected?.Invoke(this, EventArgs.Empty);
}
static void writeToClient(NamedPipeServerStream pipeStream, string msg)
{
byte[] messageBytes = Encoding.UTF8.GetBytes(msg);
pipeStream.Write(messageBytes, 0, messageBytes.Length);
pipeStream.Flush();
pipeStream.WaitForPipeDrain();
}
string? popMessageToSend()
{
string? msg;
lock (_lock_msg)
{
msg = message;
message = null;
}
return msg;
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
Stop();
clearClientEvents();
clearServerEvents();
}
disposedValue = true;
}
}
private void clearServerEvents()
{
OnServerStopped = null;
OnServerStarted = null;
}
private void clearClientEvents()
{
OnNewClient = null;
OnClientDisconnected = null;
OnMessageSend = null;
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}