Skip to content

Commit

Permalink
Update AsyncSockerServer to fix possible StackOverflow
Browse files Browse the repository at this point in the history
This reflects fixes from dotnet/runtime#74644
  • Loading branch information
rzikm committed Aug 26, 2022
1 parent 6019bf2 commit 3480a13
Showing 1 changed file with 19 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ public void Start(IPEndPoint localEndPoint)
listenSocket.Listen(100);

// post accepts on the listening socket
SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
StartAccept(null);

//Console.WriteLine("{0} connected sockets with one outstanding receive posted to each....press any key", m_outstandingReadCount);
Expand All @@ -244,22 +246,19 @@ public void Start(IPEndPoint localEndPoint)
// the accept operation on the server's listening socket</param>
public void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;

// loop while the method completes synchronously
bool willRaiseEvent = false;
while (!willRaiseEvent)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}

m_maxNumberAcceptedClients.WaitOne();
bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
m_maxNumberAcceptedClients.WaitOne();
bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
}

Expand All @@ -269,6 +268,9 @@ public void StartAccept(SocketAsyncEventArgs acceptEventArg)
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);

// Accept the next connection request
StartAccept(e);
}

private void ProcessAccept(SocketAsyncEventArgs e)
Expand All @@ -284,12 +286,10 @@ private void ProcessAccept(SocketAsyncEventArgs e)

// As soon as the client is connected, post a receive to the connection
bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs);
if(!willRaiseEvent){
if(!willRaiseEvent)
{
ProcessReceive(readEventArgs);
}

// Accept the next connection request
StartAccept(e);
}

// This method is called whenever a receive or send operation is completed on a socket
Expand Down

0 comments on commit 3480a13

Please sign in to comment.