websocket-sharp icon indicating copy to clipboard operation
websocket-sharp copied to clipboard

Receiving a large amount of frames in a short period causes StackOverflowException.

Open starshinata opened this issue 5 years ago • 2 comments

The overflow is caused by the recursive call of receive() in WebSocket.startReceiving().

private void startReceiving()
{
	if (_messageEventQueue.Count > 0)
		_messageEventQueue.Clear();

	_pongReceived = new ManualResetEvent(false);
	_receivingExited = new ManualResetEvent(false);

	Action receive = null;
	receive =
	  () =>
		WebSocketFrame.ReadFrameAsync(
		  _stream,
		  false,
		  frame =>
		  {
			  if (!processReceivedFrame(frame) || _readyState == WebSocketState.Closed)
			  {
				  var exited = _receivingExited;
				  if (exited != null)
					  exited.Set();

				  return;
			  }

			  // Receive next asap because the Ping or Close needs a response to it.
			  receive();

			  if (_inMessage || !HasMessage || _readyState != WebSocketState.Open)
				  return;

			  message();
		  },
		  ex =>
		  {
			  _logger.Fatal(ex.ToString());
			  fatal("An exception has occurred while receiving.", ex);
		  }
		);

	receive();
}

Any ideas on how to get rid of the recursion?

starshinata avatar Jul 03 '19 16:07 starshinata

We are also having this issue, any possible fixes?

WilliamPeckham avatar Jan 07 '20 09:01 WilliamPeckham

I'm facing the same problem. If you use websocket-sharp on both sides, try changing the value of the FragmentLength variable in the code. Location - WebSocket.cs file. That is, the another side must have a large frame size. The default value is 1016. I changed it to 1000000.

It seems to be working.

BenderVano avatar Jun 19 '23 02:06 BenderVano