Created
August 21, 2017 02:30
-
-
Save kg/29a7d1d51ee04eea886bd244454d4904 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task MainLoop () { | |
var readBuffer = new ArraySegment<byte>(new byte[102400]); | |
WebSocketReceiveResult wsrr; | |
if (!await Start()) { | |
WebSocket.Dispose(); | |
return; | |
} | |
using (WebSocket) | |
while (WebSocket.State == WebSocketState.Open) { | |
int readOffset = 0, count = 0; | |
try { | |
do { | |
wsrr = await WebSocket.ReceiveAsync(new ArraySegment<byte>(readBuffer.Array, readOffset, readBuffer.Count - readOffset), CancellationToken.None); | |
readOffset += wsrr.Count; | |
count += wsrr.Count; | |
} while (!wsrr.EndOfMessage); | |
} catch (Exception exc) { | |
Console.WriteLine(exc); | |
break; | |
} | |
string json = ""; | |
JObject obj = null; | |
try { | |
json = Encoding.UTF8.GetString(readBuffer.Array, 0, count); | |
obj = (JObject)JsonConvert.DeserializeObject(json); | |
} catch (Exception exc) { | |
Console.WriteLine("JSON parse error: {0}", exc); | |
Console.WriteLine("// Failed json blob below //"); | |
Console.WriteLine(json); | |
Console.WriteLine("// Failed json blob above //"); | |
} | |
if (obj == null) | |
continue; | |
var msgType = (string)obj["type"]; | |
switch (msgType) { | |
case "result": | |
var id = (int)obj["id"]; | |
IFuture f; | |
if (PendingTokens.TryGetValue(id, out f)) { | |
var result = obj["result"]; | |
if ((result != null) && f.ResultType != typeof(object)) { | |
try { | |
var res = result.ToObject(f.ResultType); | |
f.SetResult(res, null); | |
} catch (Exception exc) { | |
f.Fail(exc); | |
} | |
} else | |
f.SetResult(result, null); | |
} | |
break; | |
default: | |
if (!await OnMessage(msgType, obj)) | |
Console.WriteLine("Unhandled message {0}", msgType); | |
break; | |
} | |
} | |
Dispose(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment