private async Task UpdateAgent(ServerAgent agent, MessageClient messageClient, CancellationToken token) { var message = new AgentUpdateRequest { Filename = UpdateFilename, }; try { await messageClient.Send(message) .GetResponseAsync(token); await messageClient.DisconnectAsync(); } finally { messageClient?.Dispose(); } await Task.Delay(3000, token); // TODO: Verify update was successful by polling for server and checking version messageClient = null; try { messageClient = await Reconnect(agent, TimeSpan.FromMinutes(2)); } finally { messageClient?.Dispose(); } }
protected void RaiseOnEscUp() { if (this.OnEscUp != null) { _mClient.Dispose(); _mClient = null; this.OnEscUp(); } }
private async Task ConnectToAgent(CancellationToken token) { var agentAddress = $"{Agent.TcpHost}:{Agent.TcpPort}"; Log.Debug($"Connecting to TCP Agent '{agentAddress}'..."); try { await MessageClient.ConnectAsync(Agent.TcpHost, Agent.TcpPort, Token); Log.Info($"Connected to TCP Agent '{agentAddress}'."); Log.Debug($"Performing TCP handshake... [{agentAddress}]"); await ClientHandshake.Verify(MessageClient, token); Log.Info($"Handshake successful. [{agentAddress}]."); } catch (Exception error) { Log.Error($"Failed to connect to TCP Agent '{agentAddress}'!", error); MessageClient.Dispose(); throw; } await OnBeginSession(token); Tasks.Start(); }
private async Task <MessageClient> Reconnect(ServerAgentDefinition agent, TimeSpan timeout) { var client = new MessageClient(PhotonServer.Instance.MessageRegistry) { //Context = sessionBase, }; //MessageClient.ThreadException += MessageClient_OnThreadException; var tokenSource = new CancellationTokenSource(timeout); while (!tokenSource.IsCancellationRequested) { try { await client.ConnectAsync(agent.TcpHost, agent.TcpPort, tokenSource.Token); } catch (SocketException) { await Task.Delay(1000, tokenSource.Token); continue; } var versionRequest = new AgentGetVersionRequest(); var versionResponse = await client.Send(versionRequest) .GetResponseAsync <AgentGetVersionResponse>(tokenSource.Token); if (versionResponse.Version == UpdateVersion) { return(client); } } client.Dispose(); return(null); }
private void stopButton_Click(object sender, EventArgs e) { stopButton.Enabled = false; client.Dispose(); client = null; startButton.Enabled = true; configGroupBox.Enabled = true; clickGroupBox.Enabled = false; }
private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { // ホットキーの解除 Native.NativeMethods.UnregisterHotKey(this.Handle, HOTKEY_ID); // 設定内容の保存 SetConfig(); XmlHelper.Update(config); // 解放 client?.Dispose(); comboClient?.Dispose(); Sender.ImageRecognition.IplImages.Dispose(); }
private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout, CancellationToken token) { using (var timeoutTokenSource = new CancellationTokenSource(timeout)) using (var mergedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutTokenSource.Token, token)) { while (true) { mergedTokenSource.Token.ThrowIfCancellationRequested(); var client = new MessageClient(PhotonServer.Instance.MessageRegistry); try { using (var connectionTimeoutTokenSource = new CancellationTokenSource(20_000)) using (var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(mergedTokenSource.Token, connectionTimeoutTokenSource.Token)) { await client.ConnectAsync(agent.TcpHost, agent.TcpPort, connectTokenSource.Token); await ClientHandshake.Verify(client, connectTokenSource.Token); var versionRequest = new AgentGetVersionRequest(); var versionResponse = await client.Send(versionRequest) .GetResponseAsync <AgentGetVersionResponse>(connectTokenSource.Token); if (string.IsNullOrEmpty(versionResponse.Version)) { Log.Warn("An empty version response was received!"); continue; } if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion)) { return(client); } } } catch (SocketException) {} catch (OperationCanceledException) {} catch (Exception error) { Log.Warn("An unhandled exception occurred while attempting to reconnect to an updating agent.", error); } client.Dispose(); await Task.Delay(3_000, mergedTokenSource.Token); } } }
private async Task UpdateAgent(ServerAgent agent, MessageClient messageClient, CancellationToken token) { var message = new AgentUpdateRequest { Filename = UpdateFilename, }; try { await messageClient.Send(message) .GetResponseAsync(token); try { messageClient.Disconnect(); } catch {} } finally { messageClient?.Dispose(); messageClient = null; } Output.WriteBlock(block => block .Write("Agent update started on ", ConsoleColor.DarkCyan) .Write(agent.Name, ConsoleColor.Cyan) .WriteLine("...", ConsoleColor.DarkCyan)); await Task.Delay(6_000, token); var reconnectTimeout = TimeSpan.FromMinutes(2); try { messageClient = await Reconnect(agent, reconnectTimeout, token); } catch (OperationCanceledException) { throw new ApplicationException($"A timeout occurred after {reconnectTimeout} while waiting for the update to complete."); } finally { if (messageClient != null) { messageClient.Disconnect(); messageClient.Dispose(); } } }
private static async Task <string> GetAgentVersion(ServerAgent agent, CancellationToken token) { MessageClient messageClient = null; try { messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry); await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, token); var handshakeRequest = new HandshakeRequest { Key = Guid.NewGuid().ToString(), ServerVersion = Configuration.Version, }; var timeout = TimeSpan.FromSeconds(30); var handshakeResponse = await messageClient.Handshake <HandshakeResponse>(handshakeRequest, timeout, token); if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal)) { throw new ApplicationException("Handshake Failed! An invalid key was returned."); } if (!handshakeResponse.PasswordMatch) { throw new ApplicationException("Handshake Failed! Unauthorized."); } var agentVersionRequest = new AgentGetVersionRequest(); var agentVersionResponse = await messageClient.Send(agentVersionRequest) .GetResponseAsync <AgentGetVersionResponse>(token); return(agentVersionResponse.Version); } catch (Exception error) { throw new ApplicationException($"Failed to retrieve version of agent '{agent.Name}'!", error); } finally { messageClient?.Dispose(); } }
private async Task <object> ConnectToAgent() { Log.Debug($"Connecting to TCP Agent '{agent.TcpHost}:{agent.TcpPort}'..."); try { await MessageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, Token); Log.Info($"Connected to TCP Agent '{agent.TcpHost}:{agent.TcpPort}'."); var handshakeRequest = new HandshakeRequest { Key = Guid.NewGuid().ToString(), ServerVersion = Configuration.Version, }; var timeout = TimeSpan.FromSeconds(HandshakeTimeoutSec); var handshakeResponse = await MessageClient.Handshake <HandshakeResponse>(handshakeRequest, timeout, Token); if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal)) { throw new ApplicationException("Handshake Failed! An invalid key was returned."); } if (!handshakeResponse.PasswordMatch) { throw new ApplicationException("Handshake Failed! Unauthorized."); } } catch (Exception error) { Log.Error($"Failed to connect to TCP Agent '{agent.TcpHost}:{agent.TcpPort}'!", error); MessageClient.Dispose(); throw; } await OnBeginSession(); Tasks.Start(); return(null); }
private static async Task <string> GetAgentVersion(ServerAgent agent, CancellationToken token) { MessageClient messageClient = null; try { messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry); await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, token); await ClientHandshake.Verify(messageClient, token); var agentVersionRequest = new AgentGetVersionRequest(); var agentVersionResponse = await messageClient.Send(agentVersionRequest) .GetResponseAsync <AgentGetVersionResponse>(token); return(agentVersionResponse.Version); } catch (Exception error) { throw new ApplicationException($"Failed to retrieve version of agent '{agent.Name}'!", error); } finally { messageClient?.Dispose(); } }
public void Dispose() { Tasks?.Dispose(); messageClient?.Dispose(); }
public virtual void Dispose() { Tasks?.Dispose(); MessageClient?.Dispose(); sponsor?.Close(); }
/// <summary> /// 接收到命令 /// </summary> /// <param name="msg"></param> private void webCient_OnMessage(object sender, GFF.Model.Entity.Message msg) { Task.Factory.StartNew(() => { try { var transferStr = Encoding.UTF8.GetString(msg.Data).ToLower(); if (transferStr == "wenlirdp") { OnConnected?.Invoke(); SendImage(); } else { if (this._isHelp) { var transferArr = transferStr.Split(new string[] { ":" }, StringSplitOptions.None); var command = transferArr[0]; var dataStr = transferArr[1]; switch (command) { case "mousemove": //鼠标移动 string[] localString = dataStr.Split('@'); int localX = int.Parse(localString[0]); int localY = int.Parse(localString[1]); int remoteFormHeight = int.Parse(localString[2]); double rate = ((double)Screen.AllScreens[0].Bounds.Height) / remoteFormHeight; _MouseAndKeyHelper.SetCursorPosition((int)(localX * rate), (int)(localY * rate)); break; case "mousedown": //鼠标键的按下 if (dataStr == "left") { _MouseAndKeyHelper.MouseDown(MouseAndKeyHelper.ClickOnWhat.LeftMouse); } else if (dataStr == "middle") { _MouseAndKeyHelper.MouseDown(MouseAndKeyHelper.ClickOnWhat.MiddleMouse); } else if (dataStr == "right") { _MouseAndKeyHelper.MouseDown(MouseAndKeyHelper.ClickOnWhat.RightMouse); } break; case "mouseup": //鼠标键的抬起 if (dataStr == "left") { _MouseAndKeyHelper.MouseUp(MouseAndKeyHelper.ClickOnWhat.LeftMouse); } else if (dataStr == "middle") { _MouseAndKeyHelper.MouseUp(MouseAndKeyHelper.ClickOnWhat.MiddleMouse); } else if (dataStr == "right") { _MouseAndKeyHelper.MouseUp(MouseAndKeyHelper.ClickOnWhat.RightMouse); } break; case "keypress": //键盘键的按下即抬起 int keyValue = int.Parse(dataStr); MouseAndKeyHelper.VirtualKeys virtualKey = (MouseAndKeyHelper.VirtualKeys)(Enum.ToObject(typeof(MouseAndKeyHelper.VirtualKeys), keyValue)); _MouseAndKeyHelper.KeyPress(virtualKey); break; case "mousewheel": //鼠标滚轮的滚动 int delta = int.Parse(dataStr); _MouseAndKeyHelper.MouseWheel(delta); break; default: break; } } if (transferStr == "helpcommand") { this._isHelp = true; } if (transferStr == "stopremotehelp") { this._isHelp = false; _mCleint.Dispose(); } } } catch { } }); }
public virtual void Dispose() { Tasks?.Dispose(); SessionClient.Dispose(); MessageClient?.Dispose(); }
public async Task Update(ServerAgentDefinition agent, CancellationToken token) { //Output // .Append("Checking Agent ", ConsoleColor.DarkCyan) // .Append(agent.Name, ConsoleColor.Cyan) // .AppendLine(" for updates...", ConsoleColor.DarkCyan); //MessageClient client = null; try { //client = new MessageClient(PhotonServer.Instance.MessageRegistry) { // //Context = sessionBase, //}; //MessageClient.ThreadException += MessageClient_OnThreadException; //await client.ConnectAsync(agent.TcpHost, agent.TcpPort, token); //var versionRequest = new AgentGetVersionRequest(); //var versionResponse = await client.Send(versionRequest) // .GetResponseAsync<AgentGetVersionResponse>(token); //if (!HasUpdates(versionResponse.Version, UpdateVersion)) { // Output // .Append("Agent ", ConsoleColor.DarkBlue) // .Append(agent.Name, ConsoleColor.Blue) // .AppendLine(" is up-to-date. Version: ", ConsoleColor.DarkBlue) // .AppendLine(versionResponse.Version, ConsoleColor.Blue); // return; //} //Output // .Append("Updating Agent ", ConsoleColor.DarkCyan) // .Append(agent.Name, ConsoleColor.Cyan) // .AppendLine("...", ConsoleColor.DarkCyan); var message = new AgentUpdateRequest { Filename = MsiFilename, }; await MessageClient.Send(message) .GetResponseAsync(token); await MessageClient.DisconnectAsync(); } finally { MessageClient?.Dispose(); } await Task.Delay(3000, token); // TODO: Verify update was successful by polling for server and checking version client = null; try { client = await Reconnect(agent, TimeSpan.FromSeconds(60)); await client.DisconnectAsync(); } finally { client?.Dispose(); } Output .Append("Agent ", ConsoleColor.DarkGreen) .Append(agent.Name, ConsoleColor.Green) .AppendLine(" updated successfully.", ConsoleColor.DarkGreen); }