public void SendRequest(string ns, string method) { SocketRequest req = new SocketRequest() { socketNameSpace = ns, method = method }; SendRequest(req); }
/// <summary> /// Send a specific SocketRequest() to GPMDP /// </summary> /// <param name="req">the request to send</param> private void SendRequest(SocketRequest req) { MemoryStream ms = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SocketRequest)); ser.WriteObject(ms, req); ms.Position = 0; StreamReader reader = new StreamReader(ms); string toSend = reader.ReadToEnd(); if (ws.State == WebSocketState.Open) { ws.SendAsync(new ArraySegment <byte>(encoding.GetBytes(toSend)), WebSocketMessageType.Binary, true, CancellationToken.None); } else if (ws.State == WebSocketState.Aborted) { // do not add the overhead of repeating the command, just reconnect and they can try again if they want ws = new ClientWebSocket(); Connect(); } }
public void Connect() { ws.ConnectAsync(wsUri, CancellationToken.None); // wait until a connection is established while (ws.State == WebSocketState.Connecting) { Thread.Sleep(1); if (ws.State == WebSocketState.Closed) { ws = new ClientWebSocket(); ws.ConnectAsync(wsUri, CancellationToken.None); } } //request to control the playback SocketRequest req = new SocketRequest() { socketNameSpace = "connect", method = "connect" }; if (authCode == "") { req.arguments = new string[] { "Console" } } ; else { req.arguments = new string[] { "Console", authCode } }; SendRequest(req); //read the responses response = new SocketResponse(); MemoryStream ms = new MemoryStream(ReceiveBytes().Result); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SocketResponse)); ms.Position = 0; response = (SocketResponse)ser.ReadObject(ms); while (authCode == "") { if (response.channel == "connect") { if (response.payload.ToString().ToUpperInvariant() == "CODE_REQUIRED") {// need to send the request again with the user's code //request to control the playback req = new SocketRequest() { socketNameSpace = "connect", method = "connect", arguments = new string[] { "Console", getCode() } }; SendRequest(req); ms = new MemoryStream(ReceiveBytes().Result); ser = new DataContractJsonSerializer(typeof(SocketResponse)); ms.Position = 0; response = (SocketResponse)ser.ReadObject(ms); } else { authCode = response.payload.ToString(); req = new SocketRequest() { socketNameSpace = "connect", method = "connect", arguments = new string[] { "Console", authCode } }; SendRequest(req); } } else { ms = new MemoryStream(ReceiveBytes().Result); ser = new DataContractJsonSerializer(typeof(SocketResponse)); ms.Position = 0; response = (SocketResponse)ser.ReadObject(ms); } } }