public static async Task <SslSock> SslStartClientAsync(this ConnSock baseSock, PalSslClientAuthenticationOptions sslOptions, CancellationToken cancel = default)
        {
            SslSock ret = new SslSock(baseSock);

            await ret.StartSslClientAsync(sslOptions, cancel);

            return(ret);
        }
Example #2
0
        public static async Task <WebSocket> ConnectAsync(string uri, WebSocketConnectOptions?options = null, CancellationToken cancel = default)
        {
            if (options == null)
            {
                options = new WebSocketConnectOptions();
            }

            Uri u = new Uri(uri);

            int  port   = 0;
            bool useSsl = false;

            if (u.Scheme._IsSamei("ws"))
            {
                port = Consts.Ports.Http;
            }
            else if (u.Scheme._IsSamei("wss"))
            {
                port   = Consts.Ports.Https;
                useSsl = true;
            }
            else
            {
                throw new ArgumentException($"uri \"{uri}\" is not a WebSocket address.");
            }

            if (u.IsDefaultPort == false)
            {
                port = u.Port;
            }

            ConnSock tcpSock = await LocalNet.ConnectIPv4v6DualAsync(new TcpConnectParam(u.Host, port, connectTimeout : options.WebSocketOptions.TimeoutOpen, dnsTimeout : options.WebSocketOptions.TimeoutOpen), cancel);

            try
            {
                ConnSock targetSock = tcpSock;

                try
                {
                    if (useSsl)
                    {
                        SslSock sslSock = new SslSock(tcpSock);
                        try
                        {
                            options.SslOptions.TargetHost = u.Host;

                            await sslSock.StartSslClientAsync(options.SslOptions, cancel);

                            targetSock = sslSock;
                        }
                        catch
                        {
                            sslSock._DisposeSafe();
                            throw;
                        }
                    }

                    WebSocket webSock = new WebSocket(targetSock, options.WebSocketOptions);

                    await webSock.StartWebSocketClientAsync(uri, cancel);

                    return(webSock);
                }
                catch
                {
                    targetSock.Dispose();
                    throw;
                }
            }
            catch
            {
                tcpSock._DisposeSafe();
                throw;
            }
        }