@@ -231,7 +231,9 @@ public void Start(IPEndPoint localEndPoint)
231
231
listenSocket . Listen ( 100 ) ;
232
232
233
233
// post accepts on the listening socket
234
- StartAccept ( null ) ;
234
+ SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs ( ) ;
235
+ acceptEventArg . Completed += new EventHandler < SocketAsyncEventArgs > ( AcceptEventArg_Completed ) ;
236
+ StartAccept ( acceptEventArg ) ;
235
237
236
238
//Console.WriteLine("{0} connected sockets with one outstanding receive posted to each....press any key", m_outstandingReadCount);
237
239
Console . WriteLine ( "Press any key to terminate the server process...." ) ;
@@ -244,22 +246,19 @@ public void Start(IPEndPoint localEndPoint)
244
246
// the accept operation on the server's listening socket</param>
245
247
public void StartAccept ( SocketAsyncEventArgs acceptEventArg )
246
248
{
247
- if ( acceptEventArg == null )
249
+ // loop while the method completes synchronously
250
+ bool willRaiseEvent = false ;
251
+ while ( ! willRaiseEvent )
248
252
{
249
- acceptEventArg = new SocketAsyncEventArgs ( ) ;
250
- acceptEventArg . Completed += new EventHandler < SocketAsyncEventArgs > ( AcceptEventArg_Completed ) ;
251
- }
252
- else
253
- {
254
- // socket must be cleared since the context object is being reused
255
- acceptEventArg . AcceptSocket = null ;
256
- }
253
+ m_maxNumberAcceptedClients . WaitOne ( ) ;
257
254
258
- m_maxNumberAcceptedClients . WaitOne ( ) ;
259
- bool willRaiseEvent = listenSocket . AcceptAsync ( acceptEventArg ) ;
260
- if ( ! willRaiseEvent )
261
- {
262
- ProcessAccept ( acceptEventArg ) ;
255
+ // socket must be cleared since the context object is being reused
256
+ acceptEventArg . AcceptSocket = null ;
257
+ willRaiseEvent = listenSocket . AcceptAsync ( acceptEventArg ) ;
258
+ if ( ! willRaiseEvent )
259
+ {
260
+ ProcessAccept ( acceptEventArg ) ;
261
+ }
263
262
}
264
263
}
265
264
@@ -269,6 +268,9 @@ public void StartAccept(SocketAsyncEventArgs acceptEventArg)
269
268
void AcceptEventArg_Completed ( object sender , SocketAsyncEventArgs e )
270
269
{
271
270
ProcessAccept ( e ) ;
271
+
272
+ // Accept the next connection request
273
+ StartAccept ( e ) ;
272
274
}
273
275
274
276
private void ProcessAccept ( SocketAsyncEventArgs e )
@@ -284,12 +286,10 @@ private void ProcessAccept(SocketAsyncEventArgs e)
284
286
285
287
// As soon as the client is connected, post a receive to the connection
286
288
bool willRaiseEvent = e . AcceptSocket . ReceiveAsync ( readEventArgs ) ;
287
- if ( ! willRaiseEvent ) {
289
+ if ( ! willRaiseEvent )
290
+ {
288
291
ProcessReceive ( readEventArgs ) ;
289
292
}
290
-
291
- // Accept the next connection request
292
- StartAccept ( e ) ;
293
293
}
294
294
295
295
// This method is called whenever a receive or send operation is completed on a socket
0 commit comments