private string GetResponse(string apiVerb) { TcpClient tcpClient = new TcpClient("127.0.0.1", port); NetworkStream tcpStream = tcpClient.GetStream(); Byte[] request = Encoding.ASCII.GetBytes(apiVerb); tcpStream.Write(request, 0, request.Length); Byte[] responseBuffer = new Byte[4096]; string response = string.Empty; do { int bytesRead = tcpStream.Read(responseBuffer, 0, responseBuffer.Length); response = response + Encoding.ASCII.GetString(responseBuffer, 0, bytesRead); } while (tcpStream.DataAvailable); if (LogEvent != null) { LogEventArgs args = new LogEventArgs(); args.DateTime = DateTime.Now; args.Request = apiVerb; args.Response = response; LogEvent(this, args); } tcpClient.Close(); return response; }
private void LogApiEvent(object sender, LogEventArgs eventArgs) { ApiLogEntry logEntry = new ApiLogEntry { DateTime = eventArgs.DateTime, Request = eventArgs.Request, Response = eventArgs.Response }; ApiContext apiContext = (ApiContext)sender; logEntry.CoinName = GetCoinNameForApiContext(apiContext); logEntry.Machine = String.Format("{0}:{1}", apiContext.IpAddress, apiContext.Port); //make sure BeginInvoke is allowed if (Context != null) { Context.BeginInvoke((Action)(() => { //code to update UI //remove then add so BindingList position is on latest entry while (ApiLogEntries.Count > MaxLogEntriesOnScreen) ApiLogEntries.RemoveAt(0); ApiLogEntries.Add(logEntry); }), null); } LogApiEventToFile(logEntry); }
public string GetResponse(string apiVerb, int timeoutMs = 500) { TcpClient tcpClient = new TcpClient(this.IpAddress, Port); NetworkStream tcpStream = tcpClient.GetStream(); // set a read timeout, otherwise it is infinite and could lock the app // if a miner is locked up tcpStream.ReadTimeout = 5000; // ms Byte[] request = Encoding.ASCII.GetBytes(apiVerb); long timeoutTicks = timeoutMs * TimeSpan.TicksPerMillisecond; long ticks = DateTime.Now.Ticks; tcpStream.Write(request, 0, request.Length); Byte[] responseBuffer = new Byte[4096]; string response = string.Empty; do { int bytesRead = tcpStream.Read(responseBuffer, 0, responseBuffer.Length); response = response + Encoding.ASCII.GetString(responseBuffer, 0, bytesRead); } while ( //check timeout ((DateTime.Now.Ticks - ticks) <= timeoutTicks) && //looking for a terminating NULL character from the RPC API (String.IsNullOrEmpty(response) || (response[response.Length - 1] != '\0'))); if (LogEvent != null) { LogEventArgs args = new LogEventArgs(); args.DateTime = DateTime.Now; args.Request = apiVerb; args.Response = response; LogEvent(this, args); } tcpClient.Close(); return response; }