Skip to content
Navigation Menu
{{ message }}
forked from kerryjiang/SuperSocket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketSession.cs
More file actions
691 lines (563 loc) · 19.8 KB
/
Copy pathSocketSession.cs
File metadata and controls
691 lines (563 loc) · 19.8 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using SuperSocket.Common;
using SuperSocket.ProtoBase;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Pool;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase.Utils;
namespace SuperSocket.SocketEngine
{
static class SocketState
{
public const int Normal = 0;//0000 0000
public const int InClosing = 16;//0001 0000 >= 16
public const int Closed = 16777216;//256 * 256 * 256; 0x01 0x00 0x00 0x00
public const int InSending = 1;//0000 0001 > 1
public const int InReceiving = 2;//0000 0010 > 2
public const int InSendingReceivingMask = -4;// ~(InSending | InReceiving); 0xf0 0xff 0xff 0xff
}
/// <summary>
/// Socket Session, all application session should base on this class
/// </summary>
abstract partial class SocketSession : ISocketSession, IBufferRecycler
{
public IAppSession AppSession { get; private set; }
protected IPipelineProcessor DataProcessor { get; private set; }
protected readonly object SyncRoot = new object();
IPipelineProcessor ISocketSession.PipelineProcessor
{
get { return DataProcessor; }
}
//0x00 0x00 0x00 0x00
//1st byte: Closed(Y/N) - 0x01
//2nd byte: N/A
//3th byte: CloseReason
//Last byte: 0000 0000 - normal state
//0000 0001: in sending
//0000 0010: in receiving
//0001 0000: in closing
private int m_State = 0;
private void AddStateFlag(int stateValue)
{
while (true)
{
var oldState = m_State;
var newState = m_State | stateValue;
if (Interlocked.CompareExchange(ref m_State, newState, oldState) == oldState)
return;
}
}
private bool TryAddStateFlag(int stateValue)
{
while (true)
{
var oldState = m_State;
var newState = m_State | stateValue;
//Already marked
if (oldState == newState)
{
return false;
}
var compareState = Interlocked.CompareExchange(ref m_State, newState, oldState);
if (compareState == oldState)
return true;
}
}
private void RemoveStateFlag(int stateValue)
{
while (true)
{
var oldState = m_State;
var newState = m_State & (~stateValue);
if (Interlocked.CompareExchange(ref m_State, newState, oldState) == oldState)
return;
}
}
private bool CheckState(int stateValue)
{
return (m_State & stateValue) == stateValue;
}
protected bool SyncSend { get; private set; }
private IPool<SendingQueue> m_SendingQueuePool;
public SocketSession(Socket client)
: this(Guid.NewGuid().ToString())
{
if (client == null)
throw new ArgumentNullException("client");
m_Client = client;
LocalEndPoint = (IPEndPoint)client.LocalEndPoint;
RemoteEndPoint = (IPEndPoint)client.RemoteEndPoint;
}
public SocketSession(string sessionID)
{
SessionID = sessionID;
}
public virtual void Initialize(IAppSession appSession)
{
AppSession = appSession;
DataProcessor = appSession.CreatePipelineProcessor();
Config = appSession.Config;
SyncSend = Config.SyncSend;
m_SendingQueuePool = ((SocketServerBase)((ISocketServerAccessor)appSession.AppServer).SocketServer).SendingQueuePool;
SendingQueue queue = m_SendingQueuePool.Get();
m_SendingQueue = queue;
queue.StartEnqueue();
}
/// <summary>
/// Gets or sets the session ID.
/// </summary>
/// <value>The session ID.</value>
public string SessionID { get; private set; }
/// <summary>
/// Gets or sets the config.
/// </summary>
/// <value>
/// The config.
/// </value>
public IServerConfig Config { get; set; }
/// <summary>
/// Starts this session.
/// </summary>
public abstract void Start();
/// <summary>
/// Says the welcome information when a client connectted.
/// </summary>
protected virtual void StartSession()
{
AppSession.StartSession();
}
/// <summary>
/// Called when [close].
/// </summary>
protected virtual void OnClosed(CloseReason reason)
{
//Already closed
if (!TryAddStateFlag(SocketState.Closed))
return;
//Before changing m_SendingQueue, must check m_IsClosed
while (true)
{
var sendingQueue = m_SendingQueue;
if (sendingQueue == null)
break;
//There is no sending was started after the m_Closed ws set to 'true'
if (Interlocked.CompareExchange(ref m_SendingQueue, null, sendingQueue) == sendingQueue)
{
sendingQueue.Clear();
m_SendingQueuePool.Return(sendingQueue);
break;
}
}
var closedHandler = Closed;
if (closedHandler != null)
{
closedHandler(this, reason);
}
}
/// <summary>
/// Occurs when [closed].
/// </summary>
public Action<ISocketSession, CloseReason> Closed { get; set; }
private SendingQueue m_SendingQueue;
/// <summary>
/// Tries to send array segment.
/// </summary>
/// <param name="segments">The segments.</param>
/// <returns></returns>
public bool TrySend(IList<ArraySegment<byte>> segments)
{
if (IsClosed)
return false;
var queue = m_SendingQueue;
if (queue == null)
return false;
var trackID = queue.TrackID;
if (!queue.Enqueue(segments, trackID))
return false;
StartSend(queue, trackID, true);
return true;
}
/// <summary>
/// Tries to send array segment.
/// </summary>
/// <param name="segment">The segment.</param>
/// <returns></returns>
public bool TrySend(ArraySegment<byte> segment)
{
if (IsClosed)
return false;
var queue = m_SendingQueue;
if (queue == null)
return false;
var trackID = queue.TrackID;
if (!queue.Enqueue(segment, trackID))
return false;
StartSend(queue, trackID, true);
return true;
}
/// <summary>
/// Sends in async mode.
/// </summary>
/// <param name="queue">The queue.</param>
protected abstract void SendAsync(SendingQueue queue);
/// <summary>
/// Sends in sync mode.
/// </summary>
/// <param name="queue">The queue.</param>
protected abstract void SendSync(SendingQueue queue);
private void Send(SendingQueue queue)
{
if (SyncSend)
{
SendSync(queue);
}
else
{
SendAsync(queue);
}
}
private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)
{
if (initial)
{
if (!TryAddStateFlag(SocketState.InSending))
{
return;
}
var currentQueue = m_SendingQueue;
if (currentQueue != queue || sendingTrackID != currentQueue.TrackID)
{
//Has been sent
OnSendEnd();
return;
}
}
Socket client;
if (IsInClosingOrClosed && TryValidateClosedBySocket(out client))
{
OnSendEnd(true);
return;
}
SendingQueue newQueue = m_SendingQueuePool.Get();
var oldQueue = Interlocked.CompareExchange(ref m_SendingQueue, newQueue, queue);
if (!ReferenceEquals(oldQueue, queue))
{
if (newQueue != null)
m_SendingQueuePool.Return(newQueue);
if (IsInClosingOrClosed)
{
OnSendEnd(true);
}
else
{
OnSendEnd(false);
AppSession.Logger.Error("Failed to switch the sending queue.");
this.Close(CloseReason.InternalError);
}
return;
}
//Start to allow enqueue
newQueue.StartEnqueue();
queue.StopEnqueue();
if (queue.Count == 0)
{
AppSession.Logger.Error("There is no data to be sent in the queue.");
m_SendingQueuePool.Return(queue);
OnSendEnd(false);
this.Close(CloseReason.InternalError);
return;
}
Send(queue);
}
private void OnSendEnd()
{
OnSendEnd(IsInClosingOrClosed);
}
private void OnSendEnd(bool isInClosingOrClosed)
{
RemoveStateFlag(SocketState.InSending);
if (isInClosingOrClosed)
{
Socket client;
if (!TryValidateClosedBySocket(out client))
{
var sendingQueue = m_SendingQueue;
//No data to be sent
if (sendingQueue != null && sendingQueue.Count == 0)
{
if (client != null)// the socket instance is not closed yet, do it now
InternalClose(client, GetCloseReasonFromState(), false);
else// The UDP mode, the socket instance always is null, fire the closed event directly
OnClosed(GetCloseReasonFromState());
return;
}
return;
}
if (ValidateNotInSendingReceiving())
{
FireCloseEvent();
}
}
}
protected virtual void OnSendingCompleted(SendingQueue queue)
{
queue.Clear();
m_SendingQueuePool.Return(queue);
var newQueue = m_SendingQueue;
if (IsInClosingOrClosed)
{
Socket client;
//has data is being sent and the socket isn't closed
if (newQueue.Count > 0 && !TryValidateClosedBySocket(out client))
{
StartSend(newQueue, newQueue.TrackID, false);
return;
}
OnSendEnd(true);
return;
}
if (newQueue.Count == 0)
{
OnSendEnd();
if (newQueue.Count > 0)
{
StartSend(newQueue, newQueue.TrackID, true);
}
}
else
{
StartSend(newQueue, newQueue.TrackID, false);
}
}
public abstract void ApplySecureProtocol();
public Stream GetUnderlyStream()
{
return new NetworkStream(Client);
}
private Socket m_Client;
/// <summary>
/// Gets or sets the client.
/// </summary>
/// <value>The client.</value>
public Socket Client
{
get { return m_Client; }
}
protected bool IsInClosingOrClosed
{
get { return m_State >= SocketState.InClosing; }
}
protected bool IsClosed
{
get { return m_State >= SocketState.Closed; }
}
/// <summary>
/// Gets the local end point.
/// </summary>
/// <value>The local end point.</value>
public virtual IPEndPoint LocalEndPoint { get; protected set; }
/// <summary>
/// Gets the remote end point.
/// </summary>
/// <value>The remote end point.</value>
public virtual IPEndPoint RemoteEndPoint { get; protected set; }
/// <summary>
/// Gets or sets the secure protocol.
/// </summary>
/// <value>The secure protocol.</value>
public SslProtocols SecureProtocol { get; set; }
protected virtual bool TryValidateClosedBySocket(out Socket socket)
{
socket = m_Client;
//Already closed/closing
return socket == null;
}
public virtual void Close(CloseReason reason)
{
//Already in closing procedure
if (!TryAddStateFlag(SocketState.InClosing))
return;
Socket client;
//No need to clean the socket instance
if (TryValidateClosedBySocket(out client))
return;
//Some data is in sending
if (CheckState(SocketState.InSending))
{
//Set closing reason only, don't close the socket directly
AddStateFlag(GetCloseReasonValue(reason));
return;
}
// In the udp mode, we needn't close the socket instance
if (client != null)
InternalClose(client, reason, true);
else //In Udp mode, and the socket is not in the sending state, then fire the closed event directly
OnClosed(reason);
}
private void InternalClose(Socket client, CloseReason reason, bool setCloseReason)
{
if (Interlocked.CompareExchange(ref m_Client, null, client) == client)
{
if (setCloseReason)
AddStateFlag(GetCloseReasonValue(reason));
client.SafeClose();
if (ValidateNotInSendingReceiving())
{
OnClosed(reason);
}
}
}
protected void OnSendError(SendingQueue queue, CloseReason closeReason)
{
queue.Clear();
m_SendingQueuePool.Return(queue);
OnSendEnd();
ValidateClosed(closeReason);
}
protected virtual void OnReceiveError(CloseReason closeReason)
{
OnReceiveEnded();
ValidateClosed(closeReason);
}
protected void OnReceiveStarted()
{
AddStateFlag(SocketState.InReceiving);
}
protected void OnReceiveEnded()
{
RemoveStateFlag(SocketState.InReceiving);
}
/// <summary>
/// Validates the socket is not in the sending or receiving operation.
/// </summary>
/// <returns></returns>
private bool ValidateNotInSendingReceiving()
{
var oldState = m_State;
if ((oldState & SocketState.InSendingReceivingMask) == oldState)
{
return true;
}
return false;
}
private const int m_CloseReasonMagic = 256;
private int GetCloseReasonValue(CloseReason reason)
{
return ((int)reason + 1) * m_CloseReasonMagic;
}
private CloseReason GetCloseReasonFromState()
{
return (CloseReason)(m_State / m_CloseReasonMagic - 1);
}
private void FireCloseEvent()
{
OnClosed(GetCloseReasonFromState());
}
private void ValidateClosed(CloseReason closeReason)
{
if (IsClosed)
return;
if (CheckState(SocketState.InClosing))
{
if (ValidateNotInSendingReceiving())
{
FireCloseEvent();
}
}
else
{
Close(closeReason);
}
}
protected virtual bool IsIgnorableSocketError(int socketErrorCode)
{
if (socketErrorCode == 10004 //Interrupted
|| socketErrorCode == 10053 //ConnectionAborted
|| socketErrorCode == 10054 //ConnectionReset
|| socketErrorCode == 10058 //Shutdown
|| socketErrorCode == 10060 //TimedOut
|| socketErrorCode == 995 //OperationAborted
|| socketErrorCode == -1073741299)
{
return true;
}
return false;
}
protected virtual bool IsIgnorableException(Exception e, out int socketErrorCode)
{
socketErrorCode = 0;
if (e is ObjectDisposedException || e is NullReferenceException)
return true;
SocketException socketException = null;
if (e is IOException)
{
if (e.InnerException is ObjectDisposedException || e.InnerException is NullReferenceException)
return true;
socketException = e.InnerException as SocketException;
}
else
{
socketException = e as SocketException;
}
if (socketException == null)
return false;
socketErrorCode = socketException.ErrorCode;
if (Config.LogAllSocketException)
return false;
return IsIgnorableSocketError(socketErrorCode);
}
private const string m_SesionDataSlotName = "Session";
internal ProcessResult ProcessReceivedData(ArraySegment<byte> data, IBufferState state)
{
LocalDataStoreSlot slot = null;
try
{
slot = Thread.GetNamedDataSlot(m_SesionDataSlotName);
Thread.SetData(slot, this.AppSession);
var result = DataProcessor.Process(data, state);
if (result.State == ProcessState.Error)
{
if (string.IsNullOrEmpty(result.Message))
AppSession.Logger.Error("Protocol error");
else
AppSession.Logger.ErrorFormat("Protocol error: {0}", result.Message);
this.Close(CloseReason.ProtocolError);
}
return result;
}
catch (Exception ex)
{
LogError("Protocol error", ex);
this.Close(CloseReason.ProtocolError);
return ProcessResult.Create(ProcessState.Error);
}
finally
{
if (slot != null)
Thread.SetData(slot, null);
}
}
/// <summary>
/// Returns the buffer.
/// </summary>
/// <param name="buffers">The buffers.</param>
/// <param name="offset">The offset.</param>
/// <param name="length">The length.</param>
protected abstract void ReturnBuffer(IList<KeyValuePair<ArraySegment<byte>, IBufferState>> buffers, int offset, int length);
void IBufferRecycler.Return(IList<KeyValuePair<ArraySegment<byte>, IBufferState>> buffers, int offset, int length)
{
ReturnBuffer(buffers, offset, length);
}
}
}
You can’t perform that action at this time.
