Beispiel #1
0
        public async Task ConnectAsync(string url)
        {
            Uri    uri   = new Uri(url);
            string query = uri.PathAndQuery;
            bool   ssl   = uri.Scheme.ToLower().StartsWith("wss");
            int    port  = uri.Port > 0 ? uri.Port : (ssl ? 443 : 80);

            await client.ConnectAsync(uri.Host, port);

            ConnectionStream stream = new ConnectionStream(ref client, ssl);

            if (ssl)
            {
                await stream.Authenticate(ConnectionStream.AuthMode.Client, uri.Host);
            }

            if (!(await Handshake(stream, uri, port)))
            {
                state = WebsockState.Closed;
                throw new Exception("Failed connection at handshake");
            }

            protocol = new WebsockProtocol(ref stream);
            state    = WebsockState.Open;
            try {
                while (true)
                {
                    await OnMessage(await protocol.GetMessage());
                }
            } catch (WebsockCloseException ex) {
                await OnClose(ex.Code, ex.Reason);
            } finally {
                protocol.Dispose();
            }
        }
Beispiel #2
0
        private async Task <bool> Handshake(ConnectionStream stream, Uri uri, int port)
        {
            state = WebsockState.Connecting;
            string handshakeData = HttpHandshakeData
                                   .Replace("{Path}", uri.PathAndQuery)
                                   .Replace("{Host}", uri.Host)
                                   .Replace("{Scheme}", uri.Scheme)
                                   .Replace("{Port}", port.ToString())
                                   .Replace("{Key}", GenerateKey());
            await stream.WriteAsync(handshakeData);

            string response = Encoding.UTF8.GetString(await stream.ReadAsync());

            return(response.Split('\n')[0].Split(' ')[1] == "101");
        }
Beispiel #3
0
 public WebsockClient()
 {
     isConnected = false;
     client      = new System.Net.Sockets.TcpClient();
     state       = WebsockState.Closed;
 }