private async Task <PPError> ConnectAsyncCore(Uri uri, string[] protocols, MessageLoop connectLoop = null) { var tcs = new TaskCompletionSource <PPError>(); EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); }; try { Connection += handler; if (MessageLoop == null && connectLoop == null) { Connect(uri, protocols); } else { PPVar[] varProtocols = null; if (protocols != null) { varProtocols = new PPVar[protocols.Length]; for (int p = 0; p < protocols.Length; p++) { varProtocols[p] = new Var(protocols[p]); } } Action <PPError> action = new Action <PPError>((e) => { var result = (PPError)PPBWebSocket.Connect(this, new Var(uri.AbsoluteUri), varProtocols, varProtocols == null ? 0 : (uint)varProtocols.Length, new BlockUntilComplete() ); tcs.TrySetResult(result); } ); InvokeHelper(action, connectLoop); } return(await tcs.Task); } catch (Exception exc) { Console.WriteLine(exc.Message); tcs.SetException(exc); return(PPError.Aborted); } finally { Connection -= handler; } }
/// <summary> /// Connects to the specified WebSocket server /// </summary> /// <param name="url">The URI of the WebSocket server to connect to.</param> /// <param name="protocols"></param> public void Connect(Uri url, string[] protocols = null) { if (PPBWebSocket.IsWebSocket(this) != PPBool.True) { throw new PlatformNotSupportedException("Websocket not supported"); } if (url == null) { throw new ArgumentNullException(nameof(url)); } if (!url.IsAbsoluteUri) { throw new ArgumentException("Not Absolute URI", nameof(url)); } if (url.Scheme.ToLower() != UriSchemeWs && url.Scheme.ToLower() != UriSchemeWss) { throw new ArgumentException("Scheme invalid", nameof(url)); } PPVar[] varProtocols = null; if (protocols != null) { varProtocols = new PPVar[protocols.Length]; for (int p = 0; p < protocols.Length; p++) { varProtocols[p] = new Var(protocols[p]); } } var connectResult = (PPError)PPBWebSocket.Connect(this, new Var(url.AbsoluteUri), varProtocols, varProtocols == null ? 0 : (uint)varProtocols.Length, new CompletionCallback(OnConnect) ); }