Exemple #1
0
        public async Task InitConnection(IHttpClientFactory factory, IClientSocketFactory socketFactory)
        {
            //Retained for reconnect later on if needed
            this.socketFactory = socketFactory;
            this.httpFactory   = factory;

            // 1. Establish probe handshake

            #region Socket Handshake

            string sessionId = null;
            var    probeTURl = this.baseHttpUrl + this.probeUrl
                               + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

            var websocketKey = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();

            string initialProbeResponse = null;
            var    httpClient           = factory.CreateHttpClient();

            using (var initialProbeRequest = new HttpRequestMessage(HttpMethod.Get, probeTURl.ToString()))
            {
                try
                {
                    using (var response = await httpClient.SendAsync(initialProbeRequest, CancellationToken.None))
                    {
                        response.EnsureSuccessStatusCode();
                        initialProbeResponse = await response.Content.ReadAsStringAsync();

                        var regex = new Regex(PROBE_RESPONSE_REGEX);
                        var match = regex.Match(initialProbeResponse);

                        var initialProbeJson = JObject.Parse(match.Groups[0].Value);

                        sessionId = initialProbeJson.GetValue("sid").ToString();
                        this.keepaliveTimer.Interval = initialProbeJson.GetValue("pingInterval").ToObject <int>();

                        probeTURl = this.baseHttpUrl + this.probeUrl
                                    + new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
                                    + $"&sid={sessionId}";
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    throw ex;
                }
            }

            using (var roomRequestMessage = new HttpRequestMessage(HttpMethod.Post, probeTURl))
            {
                var roomRequest = $"15:40{this.roomPath},";
                roomRequestMessage.Content = new StringContent(roomRequest);
                //secondaryProbeRequest.Headers.Add("Content-type", "text/plain;charset=UTF-8");
                roomRequestMessage.Headers.Add("Accept", "*/*");
                roomRequestMessage.Headers.Add("DNT", "1");
                roomRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36");
                roomRequestMessage.Headers.Add("Cookie", $"io={sessionId}");

                try
                {
                    using (var response = await httpClient.SendAsync(roomRequestMessage, CancellationToken.None))
                    {
                        response.EnsureSuccessStatusCode();
                        var ok = await response.Content.ReadAsStringAsync();

                        Debug.Assert(ok.Equals("ok"));
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    throw ex;
                }
            }

            using (var protocolUpgradeRequest = new HttpRequestMessage(HttpMethod.Get, probeTURl))
            {
                protocolUpgradeRequest.Headers.Add("DNT", "1");
                protocolUpgradeRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36");
                protocolUpgradeRequest.Headers.Add("Cookie", $"io={sessionId}");
                protocolUpgradeRequest.Headers.Add("Connection", "Upgrade");
                protocolUpgradeRequest.Headers.Add("Pragma", "no-cache");
                protocolUpgradeRequest.Headers.Add("Cache-control", "no-cache");
                protocolUpgradeRequest.Headers.Add("Upgrade", "websocket");
                protocolUpgradeRequest.Headers.Add("Sec-Websocket-Version", "13");
                protocolUpgradeRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                protocolUpgradeRequest.Headers.Add("Sec-Websocket-Key", websocketKey);
                protocolUpgradeRequest.Headers.Add("Sec-Websocket-Extensions", "permessage-deflate; client_max_window_bits");

                try
                {
                    using (var response = await httpClient.SendAsync(protocolUpgradeRequest, CancellationToken.None))
                    {
                        if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
                        {
                            throw new HttpRequestException(
                                      "Did not correctly receive protocol switch from server!");
                        }

                        var accept = response.Headers.GetValues("Sec-Websocket-Accept");

                        if (!accept.Any())
                        {
                            throw new HttpRequestException("Did not get Sec-Websocket-Accept header!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    throw ex;
                }
            }

            using (var finalHandshake = new HttpRequestMessage(HttpMethod.Get, probeTURl))
            {
                finalHandshake.Headers.Add("Accept", "*/*");
                finalHandshake.Headers.Add("DNT", "1");
                finalHandshake.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3642.0 Safari/537.36");
                finalHandshake.Headers.Add("Cookie", $"io={sessionId}");
                finalHandshake.Headers.Add("Accept-Encoding", "gzip, deflate, br");

                try
                {
                    using (var response = await httpClient.SendAsync(finalHandshake, CancellationToken.None))
                    {
                        response.EnsureSuccessStatusCode();
                        var finalResponse = await response.Content.ReadAsStringAsync();

                        if (!finalResponse.Equals($"15:40{this.roomPath},"))
                        {
                            throw new HttpRequestException($"Final handshake {finalResponse} response was not expected!");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw ex;
                }
            }

            #endregion

            // 2. Upgrade connection and send ping

            this.SocketEndpointUrl = this.baseWsUrl
                                     + websocketQueryParam
                                     + $"&sid={sessionId}";

            this.websocketClient = socketFactory.CreateSocketClient();

            try
            {
                await this.websocketClient.ConnectAsync(new Uri(this.SocketEndpointUrl), CancellationToken.None);
            }
            catch (Exception connectException)
            {
                Console.Error.WriteLine(connectException);
                throw connectException;
            }

            await SendConnectionProbe();

            this.keepaliveTimer.Start();
        }
Exemple #2
0
 public Task InitConnection(IHttpClientFactory factory, IClientSocketFactory socketFactory)
 {
     throw new NotImplementedException();
 }