This repository has been archived by the owner on May 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNamedPipeManager.cs
111 lines (96 loc) · 3.01 KB
/
NamedPipeManager.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OS_Game_Launcher
{
/// <summary>
/// A very simple Named Pipe Server implementation that makes it
/// easy to pass string messages between two applications.
/// </summary>
public class NamedPipeManager
{
public string NamedPipeName = "OSGameLauncher";
public event Action<string> ReceiveString;
private const string EXIT_STRING = "__EXIT__";
private bool _isRunning = false;
private Thread Thread;
public NamedPipeManager(string name)
{
NamedPipeName = name;
}
/// <summary>
/// Starts a new Pipe server on a new thread
/// </summary>
public void StartServer()
{
Thread = new Thread((pipeName) =>
{
_isRunning = true;
while (true)
{
string text;
using (var server = new NamedPipeServerStream(pipeName as string))
{
server.WaitForConnection();
using (StreamReader reader = new StreamReader(server))
{
text = reader.ReadToEnd();
}
}
if (text == EXIT_STRING)
break;
OnReceiveString(text);
if (_isRunning == false)
break;
}
});
Thread.Start(NamedPipeName);
}
/// <summary>
/// Called when data is received.
/// </summary>
/// <param name="text"></param>
protected virtual void OnReceiveString(string text) => ReceiveString?.Invoke(text);
/// <summary>
/// Shuts down the pipe server
/// </summary>
public void StopServer()
{
_isRunning = false;
Write(EXIT_STRING);
Thread.Sleep(30); // give time for thread shutdown
}
/// <summary>
/// Write a client message to the pipe
/// </summary>
/// <param name="text"></param>
/// <param name="connectTimeout"></param>
public bool Write(string text, int connectTimeout = 300)
{
using (var client = new NamedPipeClientStream(NamedPipeName))
{
try
{
client.Connect(connectTimeout);
}
catch
{
return false;
}
if (!client.IsConnected)
return false;
using (StreamWriter writer = new StreamWriter(client))
{
writer.Write(text);
writer.Flush();
}
}
return true;
}
}
}