Beispiel #1
0
        private string RequestInternal(Uri uri, string method, byte[] data, string contentType)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);

            req.CookieContainer   = Cookies;
            req.UserAgent         = UserAgent;
            req.AllowAutoRedirect = AllowAutoRedirect;
            req.Referer           = Referer;
            req.Method            = method;
            req.ContentType       = contentType;
            SetRequest?.Invoke(this, new EventArgs <HttpWebRequest>(req));

            if ((data != null) && data.Any() && (method != WebRequestMethods.Http.Get) && (method != WebRequestMethods.Http.Head))
            {
                req.ContentLength = data.Length;
                using (Stream stream = req.GetRequestStream()) {
                    stream.Write(data, 0, data.Length);
                }
            }

            HttpWebResponse res = (HttpWebResponse)req.GetResponse();

            GotResponse?.Invoke(this, new EventArgs <HttpWebResponse>(res));
            using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding)) {
                return(sr.ReadToEnd());
            }
        }
Beispiel #2
0
        private async Task <(bool, string)> RequestInternalAsync(Uri uri, HttpMethod httpMethod, byte[] data, string contentType)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);

            req.CookieContainer   = Cookies;
            req.UserAgent         = UserAgent;
            req.AllowAutoRedirect = AllowAutoRedirect;
            req.Referer           = Referer;
            req.Method            = httpMethod.Method;
            req.ContentType       = contentType;
            SetRequest?.Invoke(this, new EventArgs <HttpWebRequest>(req));

            if (data != null && data.Any() && (httpMethod != HttpMethod.Get) && (httpMethod != HttpMethod.Head))
            {
                req.ContentLength = data.Length;
                using (Stream stream = await req.GetRequestStreamAsync().ConfigureAwait(false)) {
                    await stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
                }
            }

            HttpWebResponse res = (HttpWebResponse)(await req.GetResponseAsync().ConfigureAwait(false));

            GotResponse?.Invoke(this, new EventArgs <HttpWebResponse>(res));
            Stream responseStream = res.GetResponseStream();

            using (StreamReader sr = new StreamReader(responseStream, Encoding)) {
                string response = await sr.ReadToEndAsync().ConfigureAwait(false);

                return(IsSuccessStatusCode((int)res.StatusCode), response);
            }
        }
Beispiel #3
0
        private void HandlerMessage(object sender, MessageEventArgs e)
        {
            string Command = JsonConvert.DeserializeAnonymousType(e.Data.ToString(), new { command = string.Empty }).command.ToLower();

            GotResponse?.Invoke(this, new ResponseInfo()
            {
                Command = Command, Data = e.Data
            });
        }
Beispiel #4
0
        protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
        {
            HttpWebResponse response = (HttpWebResponse)base.GetWebResponse(request, result);

            GotResponse?.Invoke(this, new EventArgs <HttpWebResponse>(response));

            _uriContexts[request.RequestUri].Response = response;

            return(response);
        }
Beispiel #5
0
        // Callback for Read operation
        private void ReadCallback(IAsyncResult result)
        {
            if (_oldReadAsyncResult != null && result != _oldReadAsyncResult)
            {
                return;
            }

            NetworkStream networkStream;
            int           bytesread;

            var buffer = result.AsyncState as byte[];

            try
            {
                networkStream = _tcpClient.GetStream();
                bytesread     = networkStream.EndRead(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Socket error:" + ex.Message);
                return;
            }

            if (bytesread == 0)
            {
                //Debug.WriteLine(_stratumConnection.Algo + "    " + DateTime.Now + " Disconnected. Reconnecting...");

                _tcpClient.Close();
                _tcpClient = null;

                PendingAcks.Clear();

                Thread.Sleep(1000);

                ConnectToServer();

                return;
            }

            // Get the data
            var data = Encoding.ASCII.GetString(buffer, 0, bytesread);

            Debug.WriteLine($"|{_stratumConnection.Algo}| " + data);

            _page = _page + data;

            var foundClose = _page.IndexOf('}');

            while (foundClose > 0)
            {
                var currentString = _page.Substring(0, foundClose + 1);

                // We can get either a command or response from the server. Try to deserialise both
                var currentCommand  = Helpers.JsonDeserialize <StratumCommand>(currentString);
                var currentResponse = Helpers.JsonDeserialize <StratumResponse>(currentString);

                var e = new StratumEventArgs {
                    Algo = _stratumConnection.Algo
                };

                if (currentCommand.Method != null)             // We got a command
                {
                    e.MiningEventArg = currentCommand;

                    switch (currentCommand.Method)
                    {
                    case "mining.notify":
                        GotNotify?.Invoke(this, e);
                        break;

                    case "mining.set_difficulty":
                        GotSetDifficulty?.Invoke(this, e);
                        break;
                    }
                }
                else if (currentResponse.Error != null || currentResponse.Result != null)       // We got a response
                {
                    e.MiningEventArg = currentResponse;

                    // Find the command that this is the response to and remove it from the list of commands that we're waiting on a response to
                    var command = currentResponse.Id == null ? null : (string)PendingAcks[currentResponse.Id];

                    if (currentResponse.Id != null && PendingAcks.ContainsKey(currentResponse.Id))
                    {
                        PendingAcks.Remove(currentResponse.Id);
                    }

                    if (command == null)
                    {
                        Console.WriteLine("Unexpected Response");
                    }
                    else
                    {
                        GotResponse?.Invoke(command, e);

                        if (command.Contains("mining.authorize"))
                        {
                            var authSuccess = bool.Parse((e.MiningEventArg as StratumResponse)?.Result.ToString());

                            if (_lastAuthResult != authSuccess)
                            {
                                OnPingResultChanged(new PingResult(authSuccess, _stratumConnection.ToString()));
                            }

                            _lastAuthResult = authSuccess;
                        }
                    }
                }

                _page      = _page.Remove(0, foundClose + 2);
                foundClose = _page.IndexOf('}');
            }

            // Then start reading from the network again.
            _oldReadAsyncResult = networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
        }