This repository has been archived by the owner on Jul 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathEasyClientBase.cs
365 lines (284 loc) · 9.42 KB
/
EasyClientBase.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.ProtoBase;
namespace SuperSocket.ClientEngine
{
public abstract class EasyClientBase
{
private IClientSession m_Session;
private TaskCompletionSource<bool> m_ConnectTaskSource;
private TaskCompletionSource<bool> m_CloseTaskSource;
private bool m_Connected = false;
protected IPipelineProcessor PipeLineProcessor { get; set; }
#if !NETFX_CORE || NETSTANDARD
public SecurityOption Security { get; set; }
#endif
#if !SILVERLIGHT
private EndPoint m_EndPointToBind;
private EndPoint m_LocalEndPoint;
public EndPoint LocalEndPoint
{
get
{
if (m_LocalEndPoint != null)
return m_LocalEndPoint;
return m_EndPointToBind;
}
set
{
m_EndPointToBind = value;
}
}
#endif
public bool NoDelay { get; set; }
public int ReceiveBufferSize { get; set; }
public IProxyConnector Proxy { get; set; }
public Socket Socket
{
get
{
var session = m_Session;
if (session == null)
return null;
return session.Socket;
}
}
public EasyClientBase()
{
}
public bool IsConnected { get { return m_Connected; } }
#if AWAIT
public async Task<bool> ConnectAsync(EndPoint remoteEndPoint)
{
if (PipeLineProcessor == null)
throw new Exception("This client has not been initialized.");
var connectTaskSrc = InitConnect(remoteEndPoint);
return await connectTaskSrc.Task.ConfigureAwait(false);
}
#else
public Task<bool> ConnectAsync(EndPoint remoteEndPoint)
{
if (PipeLineProcessor == null)
throw new Exception("This client has not been initialized.");
var connectTaskSrc = InitConnect(remoteEndPoint);
return connectTaskSrc.Task;
}
#endif
private TcpClientSession GetUnderlyingSession()
{
#if NETFX_CORE && !NETSTANDARD
return new AsyncTcpSession();
#else
var security = Security;
if (security == null)
{
return new AsyncTcpSession();
}
#if SILVERLIGHT
// no SSL/TLS enabled
if (!security.EnabledSslProtocols)
{
return new AsyncTcpSession();
}
return new SslStreamTcpSession();
#else
// no SSL/TLS enabled
if (security.EnabledSslProtocols == System.Security.Authentication.SslProtocols.None)
{
return new AsyncTcpSession();
}
return new SslStreamTcpSession()
{
Security = security
};
#endif
#endif
}
private TaskCompletionSource<bool> InitConnect(EndPoint remoteEndPoint)
{
var session = GetUnderlyingSession();
#if !SILVERLIGHT
var localEndPoint = m_EndPointToBind;
if (localEndPoint != null)
{
session.LocalEndPoint = m_EndPointToBind;
}
#endif
session.NoDelay = NoDelay;
if (Proxy != null)
session.Proxy = Proxy;
session.Connected += new EventHandler(OnSessionConnected);
session.Error += new EventHandler<ErrorEventArgs>(OnSessionError);
session.Closed += new EventHandler(OnSessionClosed);
session.DataReceived += new EventHandler<DataEventArgs>(OnSessionDataReceived);
if (ReceiveBufferSize > 0)
session.ReceiveBufferSize = ReceiveBufferSize;
m_Session = session;
var taskSrc = m_ConnectTaskSource = new TaskCompletionSource<bool>();
session.Connect(remoteEndPoint);
return taskSrc;
}
public void Send(byte[] data)
{
Send(new ArraySegment<byte>(data, 0, data.Length));
}
public void Send(ArraySegment<byte> segment)
{
var session = m_Session;
if(!m_Connected || session == null)
throw new Exception("The socket is not connected.");
session.Send(segment);
}
public void Send(List<ArraySegment<byte>> segments)
{
var session = m_Session;
if(!m_Connected || session == null)
throw new Exception("The socket is not connected.");
session.Send(segments);
}
#if AWAIT
public async Task<bool> Close()
{
var session = m_Session;
if(session != null && m_Connected)
{
var closeTaskSrc = new TaskCompletionSource<bool>();
m_CloseTaskSource = closeTaskSrc;
session.Close();
return await closeTaskSrc.Task.ConfigureAwait(false);
}
return await Task.FromResult(false);
}
#else
public Task<bool> Close()
{
var session = m_Session;
if(session != null && m_Connected)
{
var closeTaskSrc = new TaskCompletionSource<bool>();
m_CloseTaskSource = closeTaskSrc;
session.Close();
return closeTaskSrc.Task;
}
return new Task<bool>(() => false);
}
#endif
void OnSessionDataReceived(object sender, DataEventArgs e)
{
ProcessResult result;
try
{
result = PipeLineProcessor.Process(new ArraySegment<byte>(e.Data, e.Offset, e.Length));
}
catch(Exception exc)
{
OnError(exc);
m_Session.Close();
return;
}
if (result.State == ProcessState.Error)
{
m_Session.Close();
return;
}
else if (result.State == ProcessState.Cached)
{
// allocate new receive buffer if the previous one was cached
var session = m_Session;
if (session != null)
{
var bufferSetter = session as IBufferSetter;
if (bufferSetter != null)
{
bufferSetter.SetBuffer(new ArraySegment<byte>(new byte[session.ReceiveBufferSize]));
}
}
}
if (result.Packages != null && result.Packages.Count > 0)
{
foreach (var item in result.Packages)
{
HandlePackage(item);
}
}
}
void OnSessionError(object sender, ErrorEventArgs e)
{
if (!m_Connected)
{
FinishConnectTask(false);
}
OnError(e);
}
bool FinishConnectTask(bool result)
{
var connectTaskSource = m_ConnectTaskSource;
if (connectTaskSource == null)
return false;
if (Interlocked.CompareExchange(ref m_ConnectTaskSource, null, connectTaskSource) == connectTaskSource)
{
connectTaskSource.SetResult(result);
return true;
}
return false;
}
private void OnError(Exception e)
{
OnError(new ErrorEventArgs(e));
}
private void OnError(ErrorEventArgs args)
{
var handler = Error;
if(handler != null)
handler(this, args);
}
public event EventHandler<ErrorEventArgs> Error;
void OnSessionClosed(object sender, EventArgs e)
{
m_Connected = false;
#if !SILVERLIGHT
m_LocalEndPoint = null;
#endif
var pipelineProcessor = PipeLineProcessor;
if (pipelineProcessor != null)
pipelineProcessor.Reset();
var handler = Closed;
if (handler != null)
handler(this, EventArgs.Empty);
var closeTaskSrc = m_CloseTaskSource;
if(closeTaskSrc != null)
{
if(Interlocked.CompareExchange(ref m_CloseTaskSource, null, closeTaskSrc) == closeTaskSrc)
{
closeTaskSrc.SetResult(true);
}
}
}
public event EventHandler Closed;
void OnSessionConnected(object sender, EventArgs e)
{
m_Connected = true;
#if !SILVERLIGHT
TcpClientSession session = sender as TcpClientSession;
if (session != null)
{
m_LocalEndPoint = session.LocalEndPoint;
}
#endif
FinishConnectTask(true);
var handler = Connected;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
}
public event EventHandler Connected;
protected abstract void HandlePackage(IPackageInfo package);
}
}