-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathClient.cs
229 lines (198 loc) · 7.74 KB
/
Client.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Threading;
using Castle.DynamicProxy;
namespace EasyPipes
{
/// <summary>
/// <see cref="NamedPipeClientStream"/> based IPC client
/// </summary>
public class Client
{
/// <summary>
/// Default proxy class for custom proxying. Allows intercepting calls and route them through
/// the ipc channel.
/// </summary>
/// <typeparam name="T">The ipc-service interface</typeparam>
public class Proxy<T> : IInterceptor
{
/// <summary>
/// The ipc client associated with this proxy
/// </summary>
public Client Client { get; private set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="c">The ipc client associated with this proxy</param>
public Proxy(Client c)
{
Client = c;
}
/// <summary>
/// Passes an invocation (method-call) through the IPC channel
/// </summary>
/// <param name="invocation">The call to pass on</param>
public void Intercept(IInvocation invocation)
{
invocation.ReturnValue = Intercept(invocation.Method.Name, invocation.Arguments);
}
/// <summary>
/// Passes a method-call through the IPC channel
/// </summary>
/// <param name="methodName">The method name (as recognized by Reflection)</param>
/// <param name="arguments">Array of the call parameters</param>
/// <returns>The call return</returns>
protected object Intercept(string methodName, object[] arguments)
{
// build message for intercepted call
IpcMessage msg = new IpcMessage();
msg.Service = typeof(T).Name;
msg.Method = methodName;
msg.Parameters = arguments;
// send message
return Client.SendMessage(msg);
}
}
/// <summary>
/// Name of the pipe
/// </summary>
public string PipeName { get; private set; }
/// <summary>
/// Pipe data stream
/// </summary>
protected IpcStream Stream { get; set; }
/// <summary>
/// List of types registered with serializer
/// <seealso cref="System.Runtime.Serialization.DataContractSerializer.KnownTypes"/>
/// </summary>
public List<Type> KnownTypes { get; private set; }
protected Timer timer;
/// <summary>
/// Constructor
/// </summary>
/// <param name="pipeName">Name of the pipe</param>
public Client(string pipeName)
{
PipeName = pipeName;
KnownTypes = new List<Type>();
}
/// <summary>
/// Scans the service interface and builds proxy class
/// </summary>
/// <typeparam name="T">Service interface, must equal server-side</typeparam>
/// <returns>Proxy class for remote calls</returns>
public T GetServiceProxy<T>()
{
IpcStream.ScanInterfaceForTypes(typeof(T), KnownTypes);
return (T)new ProxyGenerator().CreateInterfaceProxyWithoutTarget(typeof(T), new Proxy<T>(this));
}
/// <summary>
/// Scans the service interface and registers custom proxy class
/// </summary>
/// <typeparam name="T">Service interface, must equal server-side</typeparam>
/// <returns>Proxy class for remote calls</returns>
public void RegisterServiceProxy<T>(Proxy<T> customProxy)
{
// check if service implements interface
if (customProxy.GetType().GetInterface(typeof(T).Name) == null)
throw new InvalidOperationException("Custom Proxy class does not implement service interface");
IpcStream.ScanInterfaceForTypes(typeof(T), KnownTypes);
}
/// <summary>
/// Connect to server. This opens a persistent connection allowing multiple remote calls
/// until <see cref="Disconnect(bool)"/> is called.
/// </summary>
/// <param name="keepalive">Whether to send pings over the connection to keep it alive</param>
/// <returns>True if succeeded, false if not</returns>
public virtual bool Connect(bool keepalive = true)
{
NamedPipeClientStream source = new NamedPipeClientStream(
".",
PipeName,
PipeDirection.InOut,
PipeOptions.Asynchronous);
try
{
source.Connect(500);
} catch(TimeoutException)
{
return false;
}
Stream = new IpcStream(source, KnownTypes);
if(keepalive)
StartPing();
return true;
}
/// <summary>
/// Start timer-based keep-alive pinging. Timer is set for 0.5x the timeout time.
/// </summary>
protected void StartPing()
{
timer = new Timer(
(object state) =>
{
SendMessage(new IpcMessage { StatusMsg = StatusMessage.Ping });
},
null,
Server.ReadTimeOut / 2,
Server.ReadTimeOut / 2);
}
/// <summary>
/// Send the provided <see cref="IpcMessage"/> over the datastream
/// Opens and closes a connection if not open yet
/// </summary>
/// <param name="message">The message to send</param>
/// <returns>Return value from the Remote call</returns>
protected object SendMessage(IpcMessage message)
{
// if not connected, this is a single-message connection
bool closeStream = false;
if (Stream == null)
{
if (!Connect(false))
throw new TimeoutException("Unable to connect");
closeStream = true;
} else if( message.StatusMsg == StatusMessage.None )
{ // otherwise tell server to keep connection alive
message.StatusMsg = StatusMessage.KeepAlive;
}
IpcMessage rv;
lock (Stream)
{
Stream.WriteMessage(message);
// don't wait for answer on keepalive-ping
if (message.StatusMsg == StatusMessage.Ping)
return null;
rv = Stream.ReadMessage();
}
if (closeStream)
Disconnect(false);
if (rv.Error != null)
throw new InvalidOperationException(rv.Error);
return rv.Return;
}
/// <summary>
/// Disconnect from the server
/// </summary>
/// <param name="sendCloseMessage">Indicate whether to send a closing notification
/// to the server (if you called Connect(), this should be true)</param>
public virtual void Disconnect(bool sendCloseMessage = true)
{
// send close notification
if (sendCloseMessage)
{
// stop keepalive ping
timer?.Dispose();
IpcMessage msg = new IpcMessage() { StatusMsg = StatusMessage.CloseConnection };
Stream.WriteMessage(msg);
}
if (Stream != null)
Stream.Dispose();
Stream = null;
}
}
}