Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Here's a fix for MargieBotWebSocket to eliminate TrimStuffIDontKnowWhatItEvenIs #29

Open
AronDavis opened this issue Jan 25, 2019 · 1 comment

Comments

@AronDavis
Copy link
Contributor

AronDavis commented Jan 25, 2019

The Listen method is not properly using _webSocket.ReceiveAsync.
You're getting bad JSON because you're not checking result.EndOfMessage. So you're getting a partial message and then the "leftovers" are the things you're trying to "trim".

Below is an example solution.

private async Task Listen()
{
	ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[1024]);
	WebSocketReceiveResult result = null;

	while (_webSocket.State == WebSocketState.Open)
	{
		using (var ms = new MemoryStream())
		{
			do
			{
				result = await _webSocket.ReceiveAsync(buffer, CancellationToken.None);

				if (result.MessageType == WebSocketMessageType.Close)
				{
					await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
					break;
				}
				else
				{
					ms.Write(buffer.Array, buffer.Offset, result.Count);
				}
			}
			while (!result.EndOfMessage);

			ms.Seek(0, SeekOrigin.Begin);

			if (result.MessageType == WebSocketMessageType.Text)
			{
				using (var reader = new StreamReader(ms, Encoding.UTF8))
				{
					var stringData = await reader.ReadToEndAsync();

#if DEBUG
					Console.WriteLine($"Receive: {stringData}");
#endif

					OnMessage?.Invoke(this, stringData);
				}
			}
		}
	}
}
@AronDavis
Copy link
Contributor Author

#31 is the pull request to implement this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant