/// <summary> /// 注意:Request时ByteArrayContent,Response时ReadAsAsync<TResponse>。 /// </summary> /// <typeparam name="TResponse">post的data的类型</typeparam> /// <param name="host">用于组装Url</param> /// <param name="port">用于组装Url</param> /// <param name="controller">用于组装Url</param> /// <param name="action">用于组装Url</param> /// <param name="query">Url上的查询参数,承载登录名、时间戳、签名</param> /// <param name="data">字节数组</param> /// <param name="callback"></param> /// <param name="timeountMilliseconds"></param> public static void PostAsync <TResponse>( string host, int port, string controller, string action, Dictionary <string, string> query, object data, Action <TResponse, Exception> callback, int timeountMilliseconds = 0) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.SetTimeout(timeountMilliseconds); byte[] bytes = VirtualRoot.BinarySerializer.Serialize(data); if (bytes == null) { bytes = new byte[0]; } HttpContent content = new ByteArrayContent(bytes); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{host}:{port.ToString()}/api/{controller}/{action}{query.ToQueryString()}", content); getHttpResponse.Result.Content.ReadAsAsync <TResponse>().ContinueWith(t => { callback?.Invoke(t.Result, null); }); } } catch (Exception e) { callback?.Invoke(default, e);
public ResponseBase StopMine([FromBody] SignRequest request) { if (request == null) { return(ResponseBase.InvalidInput("参数错误")); } try { Logger.InfoDebugLine("停止挖矿"); ResponseBase response; if (!IsNTMinerOpened()) { return(ResponseBase.Ok()); } try { using (HttpClient client = RpcRoot.CreateHttpClient()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/MinerClient/StopMine", request); response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; return(response); } } catch (Exception e) { Logger.ErrorDebugLine(e); } return(ResponseBase.Ok()); } catch (Exception e) { Logger.ErrorDebugLine(e); return(ResponseBase.ServerError(e.Message)); } }
/// <summary> /// 注意:Request时ByteArrayContent,Response时ReadAsAsync<TResponse>。 /// </summary> /// <typeparam name="TResponse">post的data的类型</typeparam> /// <param name="host">用于组装Url</param> /// <param name="port">用于组装Url</param> /// <param name="controller">用于组装Url</param> /// <param name="action">用于组装Url</param> /// <param name="query">Url上的查询参数,承载登录名、时间戳、签名</param> /// <param name="data">字节数组</param> /// <param name="callback"></param> /// <param name="timeountMilliseconds"></param> public static void PostAsync <TResponse>( string host, int port, string controller, string action, Dictionary <string, string> query, object data, Action <TResponse, Exception> callback, int timeountMilliseconds = 0) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.SetTimeout(timeountMilliseconds); byte[] bytes = VirtualRoot.BinarySerializer.Serialize(data); if (bytes == null) { bytes = new byte[0]; } HttpContent content = new ByteArrayContent(bytes); Task <HttpResponseMessage> getHttpResponse = client.PostAsync(RpcRoot.GetUrl(host, port, controller, action, query), content); if (getHttpResponse.Result.IsSuccessStatusCode) { getHttpResponse.Result.Content.ReadAsAsync <TResponse>().ContinueWith(t => { callback?.Invoke(t.Result, null); }); } else { callback?.Invoke(default, new NTMinerException($"{action} http response {getHttpResponse.Result.StatusCode.ToString()} {getHttpResponse.Result.ReasonPhrase}"));
/// <summary> /// 注意:Request时原始HttpContent,Fire忽略Response /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="controller"></param> /// <param name="action"></param> /// <param name="query"></param> /// <param name="content"></param> /// <param name="callback"></param> /// <param name="timeountMilliseconds"></param> public static void FirePostAsync( string host, int port, string controller, string action, Dictionary <string, string> query, HttpContent content, Action callback = null, int timeountMilliseconds = 0) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.SetTimeout(timeountMilliseconds); Task <HttpResponseMessage> getHttpResponse = client.PostAsync(RpcRoot.GetUrl(host, port, controller, action, query), content); if (!getHttpResponse.Result.IsSuccessStatusCode) { NTMinerConsole.DevDebug($"{action} http response {getHttpResponse.Result.StatusCode.ToString()} {getHttpResponse.Result.ReasonPhrase}"); } callback?.Invoke(); } } catch { callback?.Invoke(); } }); }
static void Main() { VirtualRoot.SetOut(new ConsoleOut()); NTMinerConsole.MainUiOk(); NTMinerConsole.DisbleQuickEditMode(); try { VirtualRoot.StartTimer(); // 将服务器地址设为localhost从而使用内网ip访问免于验证用户名密码 RpcRoot.SetOfficialServerAddress(NTKeyword.Localhost); NTMinerRegistry.SetAutoBoot("NTMiner.CalcConfigUpdater", true); VirtualRoot.BuildEventPath <Per10MinuteEvent>("每10分钟更新收益计算器", LogEnum.DevConsole, location: typeof(Program), PathPriority.Normal, path: message => { UpdateAsync(); }); UpdateAsync(); NTMinerConsole.UserInfo("输入exit并回车可以停止服务!"); while (Console.ReadLine() != "exit") { } NTMinerConsole.UserOk($"服务停止成功: {DateTime.Now.ToString()}."); } catch (Exception e) { Logger.ErrorDebugLine(e); } System.Threading.Thread.Sleep(1000); }
private void CloseNTMiner() { Logger.InfoDebugLine("退出挖矿端"); bool isClosed = false; try { using (HttpClient client = RpcRoot.CreateHttpClient()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/MinerClient/CloseNTMiner", new SignRequest { }); ResponseBase response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; isClosed = response.IsSuccess(); } } catch (Exception e) { Logger.ErrorDebugLine(e); } if (!isClosed) { try { string location = NTMinerRegistry.GetLocation(); if (!string.IsNullOrEmpty(location) && File.Exists(location)) { string processName = Path.GetFileNameWithoutExtension(location); Windows.TaskKill.Kill(processName); } } catch (Exception e) { Logger.ErrorDebugLine(e); } } }
static void Main() { HomePath.SetHomeDirFullName(AppDomain.CurrentDomain.BaseDirectory); NTMinerConsole.DisbleQuickEditMode(); try { VirtualRoot.StartTimer(); // 将服务器地址设为localhost从而使用内网ip访问免于验证用户名密码 RpcRoot.SetOfficialServerAddress(NTKeyword.Localhost); NTMinerRegistry.SetAutoBoot("NTMiner.CalcConfigUpdater", true); VirtualRoot.AddEventPath <Per10MinuteEvent>("每10分钟更新收益计算器", LogEnum.DevConsole, action: message => { UpdateAsync(); }, location: typeof(Program)); UpdateAsync(); Write.UserInfo("输入exit并回车可以停止服务!"); while (Console.ReadLine() != "exit") { } Write.UserOk($"服务停止成功: {DateTime.Now.ToString()}."); } catch (Exception e) { Logger.ErrorDebugLine(e); } System.Threading.Thread.Sleep(1000); }
static void Main() { NTMinerConsole.SetIsMainUiOk(true); NTMinerConsole.DisbleQuickEditMode(); DevMode.SetDevMode(); Windows.ConsoleHandler.Register(Exit); string thisServerAddress = ServerRoot.HostConfig.ThisServerAddress; Console.Title = $"{ServerAppType.WsServer.GetName()}_{thisServerAddress}"; // 通过WsServer的网络缓解对WebApiServer的外网流量的压力。WsServer调用WebApiServer的时候走内网调用节省外网带宽 RpcRoot.SetOfficialServerAddress(ServerRoot.HostConfig.RpcServerLocalAddress); // 用本节点的地址作为队列名,消费消息时根据路由键区分消息类型 string queue = $"{ServerAppType.WsServer.GetName()}.{thisServerAddress}"; string durableQueue = queue + MqKeyword.DurableQueueEndsWith; AbstractMqMessagePath[] mqMessagePaths = new AbstractMqMessagePath[] { new ReadOnlyUserMqMessagePath(durableQueue), new MinerSignMqMessagePath(durableQueue), new WsServerNodeMqMessagePath(queue), new OperationMqMessagePath(queue), new MinerClientMqMessagePath(queue, thisServerAddress) }; if (!MqRedis.Create(ServerAppType.WsServer, mqMessagePaths, out IMqRedis mqRedis)) { NTMinerConsole.UserError("启动失败,无法继续,因为服务器上下文创建失败"); return; } MinerClientMqSender = new MinerClientMqSender(mqRedis); SpeedDataRedis = new SpeedDataRedis(mqRedis); WsServerNodeRedis = new WsServerNodeRedis(mqRedis); OperationMqSender = new OperationMqSender(mqRedis); UserMqSender = new UserMqSender(mqRedis); _wsServerNodeMqSender = new WsServerNodeMqSender(mqRedis); WsServerNodeAddressSet = new WsServerNodeAddressSet(WsServerNodeRedis, _wsServerNodeMqSender); var minerRedis = new ReadOnlyMinerRedis(mqRedis); var userRedis = new ReadOnlyUserRedis(mqRedis); VirtualRoot.StartTimer(); RpcRoot.SetRpcUser(new RpcUser(ServerRoot.HostConfig.RpcLoginName, HashUtil.Sha1(ServerRoot.HostConfig.RpcPassword))); RpcRoot.SetIsOuterNet(false); // 构造函数中异步访问redis初始化用户列表,因为是异步的所以提前构造 UserSet = new ReadOnlyUserSet(userRedis); MinerSignSet = new MinerSignSet(minerRedis); _wsServer = new SharpWsServerAdapter(ServerRoot.HostConfig); MinerClientSessionSet = new MinerClientSessionSet(_wsServer.MinerClientWsSessions); MinerStudioSessionSet = new MinerStudioSessionSet(_wsServer.MinerStudioWsSessions); _started = _wsServer.Start(); if (!_started) { NTMinerConsole.UserError("启动失败,无法继续,因为_wsServer启动失败"); return; } VirtualRoot.RaiseEvent(new WebSocketServerStatedEvent()); Console.ReadKey(true); Exit(); }
public void GetControllerNameTest() { Assert.AreEqual("FileUrl", RpcRoot.GetControllerName <IFileUrlController>()); string typeName = typeof(ICaptchaController <string>).Name; Console.WriteLine(typeName); Assert.AreEqual("Captcha", RpcRoot.GetControllerName <ICaptchaController <string> >()); }
public ResponseBase EnableWindowsRemoteDesktop(string clientIp, SignRequest request) { using (HttpClient client = RpcRoot.Create()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://{clientIp}:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{s_controllerName}/{nameof(INTMinerDaemonController.EnableWindowsRemoteDesktop)}", request); ResponseBase response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; return(response); } }
public ResponseBase StopMine(string clientIp, SignRequest request) { using (HttpClient client = RpcRoot.Create()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://{clientIp}:{NTKeyword.MinerClientPort.ToString()}/api/{s_controllerName}/{nameof(IMinerClientController.StopMine)}", request); ResponseBase response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; return(response); } }
public void TestMethod1() { using (HttpClient client = new HttpClient()) { Assert.AreEqual(100, client.Timeout.TotalSeconds); } using (HttpClient client = RpcRoot.CreateHttpClient()) { Assert.AreEqual(60, client.Timeout.TotalSeconds); } }
public ResponseBase SetMinerProfileProperty(string clientIp, SetClientMinerProfilePropertyRequest request) { using (HttpClient client = RpcRoot.Create()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://{clientIp}:{NTKeyword.MinerClientPort.ToString()}/api/{s_controllerName}/{nameof(IMinerClientController.SetMinerProfileProperty)}", request); ResponseBase response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; return(response); } }
public void TaskTest() { HttpClient client = RpcRoot.CreateHttpClient(); client.GetAsync($"http://{RpcRoot.OfficialServerAddress}/api/{RpcRoot.GetControllerName<IAppSettingController>()}/{nameof(IAppSettingController.GetTime)}") .ContinueWith(t => { Console.WriteLine(t.Result.Content.ReadAsAsync <DateTime>().Result); }).Wait(); }
public void SetAutoBootStart([FromUri] bool autoBoot, [FromUri] bool autoStart) { Logger.InfoDebugLine($"开机启动{(autoBoot ? "√" : "×")},自动挖矿{(autoStart ? "√" : "×")}"); MinerProfileUtil.SetAutoStart(autoBoot, autoStart); if (IsNTMinerOpened()) { using (HttpClient client = RpcRoot.CreateHttpClient()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/MinerClient/RefreshAutoBootStart", null); Write.DevDebug($"{nameof(SetAutoBootStart)} {getHttpResponse.Result.ReasonPhrase}"); } } }
public void CloseDaemon() { try { using (HttpClient client = RpcRoot.Create()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{s_controllerName}/{nameof(INTMinerDaemonController.CloseDaemon)}", null); Write.DevDebug($"{nameof(CloseDaemon)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Write.DevException(e); } }
private static async Task <byte[]> GetHtmlAsync(string url) { try { using (HttpClient client = RpcRoot.CreateHttpClient()) { client.Timeout = TimeSpan.FromSeconds(20); return(await client.GetByteArrayAsync(url)); } } catch (Exception e) { Logger.ErrorDebugLine(e); return(new byte[0]); } }
public void SetAutoBootStartAsync(string clientIp, bool autoBoot, bool autoStart) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{clientIp}:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{s_controllerName}/{nameof(INTMinerDaemonController.SetAutoBootStart)}?autoBoot={autoBoot}&autoStart={autoStart}", null); Write.DevDebug($"{nameof(SetAutoBootStartAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }); }
public void ShowMainWindowAsync(int clientPort, Action <bool, Exception> callback) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{clientPort.ToString()}/api/{s_controllerName}/{nameof(IMinerClientController.ShowMainWindow)}", null); bool response = getHttpResponse.Result.Content.ReadAsAsync <bool>().Result; callback?.Invoke(response, null); } } catch (Exception e) { callback?.Invoke(false, e); } }); }
public void RefreshAutoBootStartAsync() { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/{s_controllerName}/{nameof(IMinerClientController.RefreshAutoBootStart)}", null); Write.DevDebug($"{nameof(RefreshAutoBootStartAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }); }
public void SetWalletAsync(SetWalletRequest request, Action <ResponseBase, Exception> callback) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://localhost:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{s_controllerName}/{nameof(INTMinerDaemonController.SetWallet)}", request); ResponseBase response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; callback?.Invoke(response, null); } } catch (Exception e) { callback?.Invoke(null, e); } }); }
public void SaveGpuProfilesJsonAsync(string clientIp, string json) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { client.Timeout = TimeSpan.FromSeconds(3); HttpContent content = new StringContent(json); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{clientIp}:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{s_controllerName}/{nameof(INTMinerDaemonController.SaveGpuProfilesJson)}", content); Write.DevDebug($"{nameof(SaveGpuProfilesJsonAsync)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }); }
public void TestMethod1() { using (HttpClient client = new HttpClient()) { Assert.AreEqual(100, client.Timeout.TotalSeconds); } using (HttpClient client = RpcRoot.CreateHttpClient()) { Assert.AreEqual(10, client.Timeout.TotalSeconds); client.SetTimeout(5000); Assert.AreEqual(5000, client.Timeout.TotalMilliseconds); } using (HttpClient client = RpcRoot.CreateHttpClient()) { // 0不起作用 client.SetTimeout(0); Assert.AreEqual(10, client.Timeout.TotalSeconds); } }
public void CloseServices() { try { Process[] processes = Process.GetProcessesByName("NTMinerServices"); if (processes.Length == 0) { return; } using (HttpClient client = RpcRoot.Create()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.ControlCenterPort.ToString()}/api/{SControllerName}/{nameof(IControlCenterController.CloseServices)}", null); Write.DevDebug($"{nameof(CloseServices)} {getHttpResponse.Result.ReasonPhrase}"); } } catch (Exception e) { Logger.ErrorDebugLine(e); } }
public ResponseBase StartMine([FromBody] WorkRequest request) { if (request == null) { return(ResponseBase.InvalidInput("参数错误")); } try { Logger.InfoDebugLine("开始挖矿"); ResponseBase response; if (request.WorkId != Guid.Empty) { File.WriteAllText(SpecialPath.NTMinerLocalJsonFileFullName, request.LocalJson); File.WriteAllText(SpecialPath.NTMinerServerJsonFileFullName, request.ServerJson); } string location = NTMinerRegistry.GetLocation(); if (IsNTMinerOpened()) { using (HttpClient client = RpcRoot.CreateHttpClient()) { WorkRequest innerRequest = new WorkRequest { WorkId = request.WorkId }; Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/MinerClient/StartMine", innerRequest); response = getHttpResponse.Result.Content.ReadAsAsync <ResponseBase>().Result; return(response); } } else { if (!string.IsNullOrEmpty(location) && File.Exists(location)) { string arguments = NTKeyword.AutoStartCmdParameterName; if (request.WorkId != Guid.Empty) { arguments += " --work"; } Windows.Cmd.RunClose(location, arguments); return(ResponseBase.Ok()); } return(ResponseBase.ServerError("挖矿端程序不存在")); } } catch (Exception e) { Logger.ErrorDebugLine(e); return(ResponseBase.ServerError(e.Message)); } }
private static void GetAsync <T>(string controller, string action, Dictionary <string, string> param, Action <T, Exception> callback) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { string queryString = string.Empty; if (param != null && param.Count != 0) { queryString = "?" + string.Join("&", param.Select(a => a.Key + "=" + a.Value)); } Task <HttpResponseMessage> getHttpResponse = client.GetAsync($"http://{NTKeyword.OfficialServerHost}:{NTKeyword.ControlCenterPort.ToString()}/api/{controller}/{action}{queryString}"); T response = getHttpResponse.Result.Content.ReadAsAsync <T>().Result; callback?.Invoke(response, null); } } catch (Exception e) { callback?.Invoke(default, e);
public Task <SpeedData> GetSpeedAsync(string clientHost, Action <SpeedData, Exception> callback) { return(Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{clientHost}:{NTKeyword.MinerClientPort.ToString()}/api/{s_controllerName}/{nameof(IMinerClientController.GetSpeed)}", null); SpeedData data = getHttpResponse.Result.Content.ReadAsAsync <SpeedData>().Result; callback?.Invoke(data, null); return data; } } catch (Exception e) { callback?.Invoke(null, e); return null; } })); }
public void SaveGpuProfilesJson() { try { Logger.InfoDebugLine("保存显卡参数"); string json = Request.Content.ReadAsStringAsync().Result; SpecialPath.SaveGpuProfilesJsonFile(json); if (IsNTMinerOpened()) { using (HttpClient client = RpcRoot.CreateHttpClient()) { Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://localhost:{NTKeyword.MinerClientPort.ToString()}/api/MinerClient/OverClock", null); Write.DevDebug($"{nameof(SaveGpuProfilesJson)} {getHttpResponse.Result.ReasonPhrase}"); } } } catch (Exception e) { Logger.ErrorDebugLine(e); } }
public void ReportSpeedAsync(string host, SpeedData data, Action <ReportResponse> callback) { Task.Factory.StartNew(() => { TimeSpan timeSpan = TimeSpan.FromSeconds(3); try { using (HttpClient client = RpcRoot.Create()) { // 可能超过3秒钟,查查原因。因为我的网络不稳经常断线。 client.Timeout = timeSpan; Task <HttpResponseMessage> getHttpResponse = client.PostAsJsonAsync($"http://{host}:{NTKeyword.ControlCenterPort.ToString()}/api/{SControllerName}/{nameof(IReportController.ReportSpeed)}", data); ReportResponse response = getHttpResponse.Result.Content.ReadAsAsync <ReportResponse>().Result; callback?.Invoke(response); } } catch (Exception e) { Write.DevException(e); } }); }
public void GetGpuProfilesJsonAsync(string clientIp, Action <GpuProfilesJsonDb, Exception> callback) { Task.Factory.StartNew(() => { try { using (HttpClient client = RpcRoot.Create()) { client.Timeout = TimeSpan.FromSeconds(3); Task <HttpResponseMessage> getHttpResponse = client.PostAsync($"http://{clientIp}:{NTKeyword.NTMinerDaemonPort.ToString()}/api/{s_controllerName}/{nameof(INTMinerDaemonController.GetGpuProfilesJson)}", null); string json = getHttpResponse.Result.Content.ReadAsAsync <string>().Result; GpuProfilesJsonDb data = VirtualRoot.JsonSerializer.Deserialize <GpuProfilesJsonDb>(json); callback?.Invoke(data, null); return(data); } } catch (Exception e) { callback?.Invoke(null, e); return(null); } }); }