From f571e0bec07b6a4494860e0e803002352bf45aac Mon Sep 17 00:00:00 2001 From: RogueException Date: Wed, 16 Sep 2015 04:24:47 -0300 Subject: [PATCH] Fixed built-in websocket reuse --- .../Net/WebSockets/WebSocket.BuiltIn.cs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/Discord.Net/Net/WebSockets/WebSocket.BuiltIn.cs b/src/Discord.Net/Net/WebSockets/WebSocket.BuiltIn.cs index 725b0e330..50af998cd 100644 --- a/src/Discord.Net/Net/WebSockets/WebSocket.BuiltIn.cs +++ b/src/Discord.Net/Net/WebSockets/WebSocket.BuiltIn.cs @@ -17,9 +17,9 @@ namespace Discord.Net.WebSockets private const int HR_TIMEOUT = -2147012894; private readonly ConcurrentQueue _sendQueue; - private readonly ClientWebSocket _webSocket; private readonly int _sendInterval; - + private ClientWebSocket _webSocket; + public event EventHandler ProcessMessage; private void RaiseProcessMessage(string msg) { @@ -31,12 +31,12 @@ namespace Discord.Net.WebSockets { _sendInterval = sendInterval; _sendQueue = new ConcurrentQueue(); - _webSocket = new ClientWebSocket(); - _webSocket.Options.KeepAliveInterval = TimeSpan.Zero; } public Task Connect(string host, CancellationToken cancelToken) { + _webSocket = new ClientWebSocket(); + _webSocket.Options.KeepAliveInterval = TimeSpan.Zero; return _webSocket.ConnectAsync(new Uri(host), cancelToken); } @@ -44,7 +44,9 @@ namespace Discord.Net.WebSockets { byte[] ignored; while (_sendQueue.TryDequeue(out ignored)) { } - return TaskHelper.CompletedTask; + _webSocket.Dispose(); + _webSocket = new ClientWebSocket(); + return TaskHelper.CompletedTask; } public Task[] RunTasks(CancellationToken cancelToken) @@ -60,7 +62,7 @@ namespace Discord.Net.WebSockets { return Task.Run(async () => { - var buffer = new ArraySegment(new byte[ReceiveChunkSize]); + var buffer = new byte[ReceiveChunkSize]; //new ArraySegment(new byte[ReceiveChunkSize]); var builder = new StringBuilder(); try @@ -75,7 +77,7 @@ namespace Discord.Net.WebSockets try { - result = await _webSocket.ReceiveAsync(buffer, cancelToken).ConfigureAwait(false); + result = await _webSocket.ReceiveAsync(new ArraySegment(buffer), cancelToken).ConfigureAwait(false); } catch (Win32Exception ex) when (ex.HResult == HR_TIMEOUT) { @@ -85,11 +87,11 @@ namespace Discord.Net.WebSockets if (result.MessageType == WebSocketMessageType.Close) throw new Exception($"Got Close Message ({result.CloseStatus?.ToString() ?? "Unexpected"}, {result.CloseStatusDescription ?? "No Reason"})"); else - builder.Append(Encoding.UTF8.GetString(buffer.Array, buffer.Offset, result.Count)); + builder.Append(Encoding.UTF8.GetString(buffer, 0, result.Count)); } while (result == null || !result.EndOfMessage); - + RaiseProcessMessage(builder.ToString()); builder.Clear();