forked from kerryjiang/SuperSocket.ClientEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEasyClientBase.cs
More file actions
306 lines (237 loc) · 7.96 KB
/
EasyClientBase.cs
File metadata and controls
306 lines (237 loc) · 7.96 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperSocket.ProtoBase;
using System.Net;
using System.Threading;
namespace SuperSocket.ClientEngine
{
public abstract class EasyClientBase : IBufferState
{
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
public SecurityOption Security { get; set; }
#endif
#if !SILVERLIGHT
public EndPoint LocalEndPoint { get; set; }
#endif
#if !__IOS__
public bool NoDelay { get; set; }
#endif
public int ReceiveBufferSize { get; set; }
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 = m_ConnectTaskSource = 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 = m_ConnectTaskSource = InitConnect(remoteEndPoint);
return connectTaskSrc.Task;
}
#endif
private TcpClientSession GetUnderlyingSession()
{
#if NETFX_CORE
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 = LocalEndPoint;
if (localEndPoint != null)
{
session.LocalEndPoint = localEndPoint;
}
#endif
#if !__IOS__
session.NoDelay = NoDelay;
#endif
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;
session.Connect(remoteEndPoint);
return new TaskCompletionSource<bool>();
}
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>();
session.Close();
m_CloseTaskSource = closeTaskSrc;
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>();
session.Close();
m_CloseTaskSource = closeTaskSrc;
return closeTaskSrc.Task;
}
return new Task<bool>(() => false);
}
#endif
void OnSessionDataReceived(object sender, DataEventArgs e)
{
var result = PipeLineProcessor.Process(new ArraySegment<byte>(e.Data, e.Offset, e.Length), this as IBufferState);
// allocate new receive buffer if the previous one was cached
if (result.State == ProcessState.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]));
}
}
}
}
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;
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)
{
LocalEndPoint = session.LocalEndPoint;
}
#endif
FinishConnectTask(true);
var handler = Connected;
if(handler != null)
{
handler(this, EventArgs.Empty);
}
}
public event EventHandler Connected;
int IBufferState.DecreaseReference()
{
return 0;
}
void IBufferState.IncreaseReference()
{
}
}
}