-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathAsyncSocketServer.cs
More file actions
305 lines (244 loc) · 10.1 KB
/
AsyncSocketServer.cs
File metadata and controls
305 lines (244 loc) · 10.1 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
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketEngine.AsyncSocket;
namespace SuperSocket.SocketEngine
{
class AsyncSocketServer : TcpSocketServerBase, IActiveConnector
{
public AsyncSocketServer(IAppServer appServer, ListenerInfo[] listeners)
: base(appServer, listeners)
{
}
private BufferManager m_BufferManager;
private ConcurrentStack<SocketAsyncEventArgsProxy> m_ReadWritePool;
public override bool Start()
{
try
{
int bufferSize = AppServer.Config.ReceiveBufferSize;
if (bufferSize <= 0)
bufferSize = 1024 * 4;
m_BufferManager = new BufferManager(bufferSize * AppServer.Config.MaxConnectionNumber, bufferSize);
try
{
m_BufferManager.InitBuffer();
}
catch (Exception e)
{
AppServer.Logger.Error("Failed to allocate buffer for async socket communication, may because there is no enough memory, please decrease maxConnectionNumber in configuration!", e);
return false;
}
// preallocate pool of SocketAsyncEventArgs objects
SocketAsyncEventArgs socketEventArg;
var socketArgsProxyList = new List<SocketAsyncEventArgsProxy>(AppServer.Config.MaxConnectionNumber);
for (int i = 0; i < AppServer.Config.MaxConnectionNumber; i++)
{
//Pre-allocate a set of reusable SocketAsyncEventArgs
socketEventArg = new SocketAsyncEventArgs();
m_BufferManager.SetBuffer(socketEventArg);
socketArgsProxyList.Add(new SocketAsyncEventArgsProxy(socketEventArg));
}
m_ReadWritePool = new ConcurrentStack<SocketAsyncEventArgsProxy>(socketArgsProxyList);
if (!base.Start())
return false;
IsRunning = true;
return true;
}
catch (Exception e)
{
AppServer.Logger.Error(e);
return false;
}
}
protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state)
{
if (IsStopped)
return;
ProcessNewClient(client, listener.Info.Security);
}
private IAppSession ProcessNewClient(Socket client, SslProtocols security)
{
//Get the socket for the accepted client connection and put it into the
//ReadEventArg object user token
SocketAsyncEventArgsProxy socketEventArgsProxy;
if (!m_ReadWritePool.TryPop(out socketEventArgsProxy))
{
AppServer.AsyncRun(client.SafeClose);
if (AppServer.Logger.IsErrorEnabled)
AppServer.Logger.ErrorFormat("Max connection number {0} was reached!", AppServer.Config.MaxConnectionNumber);
return null;
}
ISocketSession socketSession;
IAppSession session=null;
try
{
if (security == SslProtocols.None)
socketSession = new AsyncSocketSession(client, socketEventArgsProxy);
else
socketSession = new AsyncStreamSocketSession(client, security, socketEventArgsProxy);
session = CreateSession(client, socketSession);
}
catch
{
socketEventArgsProxy.Reset();
this.m_ReadWritePool.Push(socketEventArgsProxy);
AppServer.AsyncRun(client.SafeClose);
return null;
}
if (session == null)
{
socketEventArgsProxy.Reset();
this.m_ReadWritePool.Push(socketEventArgsProxy);
AppServer.AsyncRun(client.SafeClose);
return null;
}
socketSession.Closed += SessionClosed;
var negotiateSession = socketSession as INegotiateSocketSession;
if (negotiateSession == null)
{
if (RegisterSession(session))
{
AppServer.AsyncRun(() => socketSession.Start());
}
return session;
}
negotiateSession.NegotiateCompleted += OnSocketSessionNegotiateCompleted;
negotiateSession.Negotiate();
return null;
}
private void OnSocketSessionNegotiateCompleted(object sender, EventArgs e)
{
var socketSession = sender as ISocketSession;
var negotiateSession = socketSession as INegotiateSocketSession;
if (!negotiateSession.Result)
{
socketSession.Close(CloseReason.SocketError);
return;
}
if (RegisterSession(negotiateSession.AppSession))
{
AppServer.AsyncRun(() => socketSession.Start());
}
}
private bool RegisterSession(IAppSession appSession)
{
if (AppServer.RegisterSession(appSession))
return true;
appSession.SocketSession.Close(CloseReason.InternalError);
return false;
}
public override void ResetSessionSecurity(IAppSession session, SslProtocols security)
{
ISocketSession socketSession;
var socketAsyncProxy = ((IAsyncSocketSessionBase)session.SocketSession).SocketAsyncProxy;
if (security == SslProtocols.None)
socketSession = new AsyncSocketSession(session.SocketSession.Client, socketAsyncProxy, true);
else
socketSession = new AsyncStreamSocketSession(session.SocketSession.Client, security, socketAsyncProxy, true);
socketSession.Initialize(session);
socketSession.Start();
}
void SessionClosed(ISocketSession session, CloseReason reason)
{
var socketSession = session as IAsyncSocketSessionBase;
if (socketSession == null)
return;
var proxy = socketSession.SocketAsyncProxy;
proxy.Reset();
var args = proxy.SocketEventArgs;
var serverState = AppServer.State;
var pool = this.m_ReadWritePool;
if (pool == null || serverState == ServerState.Stopping || serverState == ServerState.NotStarted)
{
if(!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
args.Dispose();
return;
}
if (proxy.OrigOffset != args.Offset)
{
args.SetBuffer(proxy.OrigOffset, AppServer.Config.ReceiveBufferSize);
}
if (!proxy.IsRecyclable)
{
//cannot be recycled, so release the resource and don't return it to the pool
args.Dispose();
return;
}
pool.Push(proxy);
}
public override void Stop()
{
if (IsStopped)
return;
lock (SyncRoot)
{
if (IsStopped)
return;
base.Stop();
foreach (var item in m_ReadWritePool)
item.SocketEventArgs.Dispose();
m_ReadWritePool = null;
m_BufferManager = null;
IsRunning = false;
}
}
class ActiveConnectState
{
public TaskCompletionSource<ActiveConnectResult> TaskSource { get; private set; }
public Socket Socket { get; private set; }
public ActiveConnectState(TaskCompletionSource<ActiveConnectResult> taskSource, Socket socket)
{
TaskSource = taskSource;
Socket = socket;
}
}
Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
{
return ((IActiveConnector)this).ActiveConnect(targetEndPoint, null);
}
Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint, EndPoint localEndPoint)
{
var taskSource = new TaskCompletionSource<ActiveConnectResult>();
var socket = new Socket(targetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (localEndPoint != null)
{
socket.ExclusiveAddressUse = false;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.Bind(localEndPoint);
}
socket.BeginConnect(targetEndPoint, OnActiveConnectCallback, new ActiveConnectState(taskSource, socket));
return taskSource.Task;
}
private void OnActiveConnectCallback(IAsyncResult result)
{
var connectState = result.AsyncState as ActiveConnectState;
try
{
var socket = connectState.Socket;
socket.EndConnect(result);
var session = ProcessNewClient(socket, SslProtocols.None);
if (session == null)
connectState.TaskSource.SetException(new Exception("Failed to create session for this socket."));
else
connectState.TaskSource.SetResult(new ActiveConnectResult { Result = true, Session = session });
}
catch (Exception e)
{
connectState.TaskSource.SetException(e);
}
}
}
}