forked from lempamo/ChaosIV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PipeServer.cs
74 lines (61 loc) · 1.73 KB
/
PipeServer.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
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace ChaosIV
{
class PipeServer
{
private readonly NamedPipeServerStream _pipe;
private StreamReader _pipeReader;
private StreamWriter _pipeWriter;
private readonly GTA.Timer _pipeTimer = new GTA.Timer();
public static readonly int PIPE_INTERVAL = 200;
private Task<string> _readPipeTask;
public Action<string> OnMessage;
public PipeServer() {
try {
_pipe = new NamedPipeServerStream("ChaosIVTwitchPollProxyPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
var asyncResult = _pipe.BeginWaitForConnection((IAsyncResult result) => {
GTA.Game.Console.Print("Pipe connected.");
_pipe.EndWaitForConnection(result);
_pipeReader = new StreamReader(_pipe);
_pipeWriter = new StreamWriter(_pipe) {
AutoFlush = true
};
_pipeTimer.Tick += new EventHandler(OnElapsed);
_pipeTimer.Interval = PIPE_INTERVAL;
_pipeTimer.Start();
}, null);
}
catch (Exception ex) {
ChaosMain.ReportException(ex);
}
}
public void Send(string message) {
_pipeWriter.WriteLine(message);
}
private void OnElapsed(object s, EventArgs e) {
try {
if (_readPipeTask == null) {
_readPipeTask = _pipeReader.ReadLineAsync();
}
else if (_readPipeTask.IsCompleted) {
OnMessage?.Invoke(_readPipeTask.Result);
_readPipeTask = null;
}
}
catch (Exception ex) {
ChaosMain.ReportException(ex);
//Close();
}
}
public bool IsConnected() {
return _pipe.IsConnected;
}
public void Close() {
_pipeTimer.Stop();
_pipe.Dispose();
}
}
}