internal static void Run(ClientArgs args) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(new IPEndPoint(args.ServerAddress, args.ServerPort)); try { switch (args.TestType) { case TestType.Upload: ClientTest.Upload(new TcpSocket(client), args.SizeInMb); break; case TestType.Download: ClientTest.Download(new TcpSocket(client), args.SizeInMb); break; case TestType.Integrity: ClientTest.Integrity(new TcpSocket(client), args.SizeInMb); break; } } finally { client.Close(); } }
private void ExeRegister(ClientEvent eEvent) { //Log Log.Info("thread" + Thread.CurrentThread.ManagedThreadId + " exe reigister event", eEvent.Client.LogSource); //OP RegisterArgs args = ClientArgs.AnalysisBody <RegisterArgs>(eEvent.Body); DbResult <string> result = DbUserAction.Register(args.Name, args.Password, args.Sex, args.City, args.UserType); if (result.Status == DbEnum.Success) { eEvent.Client.Send(new ServerEvent() { Type = Event_Type.Register, RawContent = ClientArgs.ToBody(new RegisterArgs() { User_ID = result.Data, ErrorCode = ClientArgs.ArgSuccess }), SendTime = DateTime.Now.ToString() }.ToString()); } else { eEvent.Client.Send(new ServerEvent() { Type = Event_Type.Register, RawContent = ClientArgs.ToBody(new BadRequestArgs() { Code = result.ErrorCode, Message = result.Error }), SendTime = DateTime.Now.ToString() }.ToString()); } }
private ServerEvent NewEvent(Event_Type type, ClientArgs args) { return(new ServerEvent() { Type = type, RawContent = ClientArgs.ToBody(args), SendTime = DateTime.Now.ToString() }); }
protected virtual void OnRetriveClientID(ClientArgs args) { if (RetriveClientID != null) { RetriveClientID(this, args); } }
public static async Task <Client> Connect() { while (true) { var clientProcess = await GetLeagueClientProcess(); var match = InstallDirectoryRegex.Match(clientProcess.GetCommandLine()); var installDirectory = match.Groups["path"]; var lockfile = $"{installDirectory}lockfile"; if (File.Exists(lockfile)) { string lockText; using (var lockfileStream = new FileStream(lockfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var textStream = new StreamReader(lockfileStream)) { lockText = await textStream.ReadToEndAsync(); } } var parts = lockText.Split(':'); var args = new ClientArgs { Process = parts[0], Pid = int.Parse(parts[1]), Port = ushort.Parse(parts[2]), Password = parts[3], Protocol = parts[4], }; var connectionString = $"127.0.0.1:{args.Port}/"; var client = new HttpClient { BaseAddress = new Uri($"{args.Protocol}://{connectionString}"), DefaultRequestHeaders = { { "Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"riot:{args.Password}"))}" } }, }; var socket = new ClientWebSocket(); var uri = new Uri($"ws://{connectionString}"); socket.Options.UseDefaultCredentials = false; socket.Options.SetRequestHeader("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"riot:{args.Password}"))}"); //await socket.ConnectAsync(uri, CancellationToken.None); return(new Client(client, socket)); } await Task.Delay(1000); } }
private void logOnCommand(object sender, ClientArgs e) { if (e.CommandID == (int)CommandEnum.LogCommand) { List <Log> logsList = JsonConvert.DeserializeObject <List <Log> >(e.Args); foreach (Log log in logsList) { m_logs.Add(log); } } }
public static void Main(string[] args) { System.Console.WriteLine("Starting Client with args: '{0}'", args.ToSingleLineStrin()); var clientArgs = new ClientArgs(args); System.Console.WriteLine("Starting Client with ClientArgs: '{0}'", clientArgs); //System.Console.WriteLine("Starting ClientPrefix: '{0}', ClientsCount: '{1}', ClientReadingTimeout: '{2}', DelayBetweenClients: '{3}', ClientsRunTime: '{4}'", clientArgs.ClientsPrefix, clientArgs.ClientsCount, clientArgs.ClientReadingTimeout, clientArgs.DelayBetweenClients, clientArgs.ClientsRuntime); var clients = new List <LongPollingClient>(clientArgs.ClientsCount); var hostname = Dns.GetHostName(); for (var index = 0; index < clientArgs.ClientsCount; ++index) { //var UserID = string.Format("({0})#{1}", clientArgs.ClientsPrefix, index); //var client = new Client(new User(UserID), clientArgs.ClientReadingTimeout, new NotificationServiceClient("NetTcpBinding_INotificationService")); var user = new User(hostname, clientArgs.SetIndex, index); LongPollingClient client; client = new LongPollingClient(user, clientArgs.ClientReadingTimeout, new NotificationServiceClient("NetTcpBinding_INotificationService")); client.Start(); System.Console.WriteLine("Client with User: '******' is started", user); Thread.Sleep(clientArgs.DelayBetweenClients); } System.Console.WriteLine("ClientPrefix: '{0}', '{1}' clients were created and started", clientArgs.ClientsPrefix, clientArgs.ClientsCount); var now = DateTime.Now; var epsilon = TimeSpan.FromMinutes(5); var runtime = clientArgs.ClientsRuntime + epsilon; System.Console.WriteLine("ClientPrefix: '{0}' is running for '{1}', Expected stop: '{2}', Now: '{3}', epsilon: '{4}', runtime with epsilon: '{5}'", clientArgs.ClientsPrefix, clientArgs.ClientsRuntime, now + clientArgs.ClientsRuntime, now, epsilon, runtime); if (Task.WaitAll(clients.Select(c => c.Task).ToArray(), runtime)) { System.Console.WriteLine("ClientPrefix: '{0}' finished waiting successfully for all '{1}' clients.", clientArgs.ClientsPrefix, clientArgs.ClientsCount); } else { System.Console.WriteLine("ClientsPrefix: '{0}' did not finish waiting for all '{1}' clients.", clientArgs.ClientsCount); } Console.WriteLine("Press enter to quit."); Console.ReadLine(); }
/// <summary> /// Settingses the on command. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private void settingsOnCommand(object sender, ClientArgs e) { if (e.CommandID == (int)CommandEnum.GetConfigCommand) { setting = JsonConvert.DeserializeObject <Setting>(e.Args); } else if (e.CommandID == (int)CommandEnum.RemoveHandler) { Application.Current.Dispatcher.Invoke(new Action(() => { modelSettingsHandlers.Remove(e.Args); })); } }
/// <summary> /// Logs the on command. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private void logOnCommand(object sender, ClientArgs e) { if (e.CommandID == (int)CommandEnum.LogCommand) { List <Log> logsList = JsonConvert.DeserializeObject <List <Log> >(e.Args); Application.Current.Dispatcher.Invoke(new Action(() => { foreach (Log log in logsList) { model_log.Add(log); } })); } }
private void StartClient() { var args = new ClientArgs(); args.serverIP = textBoxServerIP.Text; if (!Int32.TryParse(textBoxXmitConnectionCount.Text, out args.xmitConnectionCount)) { MessageBox.Show("Parse error of Xmit connection count"); return; } if (args.xmitConnectionCount < 1) { MessageBox.Show("Xmit connection count must be integer value greater than 0"); return; } if (!Int32.TryParse(textBoxXmitFragmentMB.Text, out args.xmitFragmentMB)) { MessageBox.Show("Parse error of Xmit fragment size (MB)"); return; } if (args.xmitFragmentMB < 1) { MessageBox.Show("Xmit fragment size (MB) must be integer value greater than 0"); return; } if (1000 < args.xmitFragmentMB) { MessageBox.Show("Xmit fragment size (MB) must be integer value smaller than 1000"); return; } args.sendFilePath = textBoxSendFile.Text; mBackgroundWorker = new BackgroundWorker(); mBackgroundWorker.DoWork += Client_DoWork; mBackgroundWorker.WorkerReportsProgress = true; mBackgroundWorker.ProgressChanged += Client_ProgressChanged; mBackgroundWorker.RunWorkerCompleted += Client_RunWorkerCompleted; buttonStart.IsEnabled = false; mBackgroundWorker.RunWorkerAsync(args); }
private static async Task Client_MessageCreate(Client client, ClientArgs <Message> args) { client.Logger.Log(LoggingLevel.Dcs, args.Data.Content); Message message = args.Data; if (message.ChannelId == 814019791958441994) { await args.Data.Channel.Messages.Delete(message); Message updateMessage = new() { Id = 836360623100133376, Content = message.Content }; await args.Data.Channel.Messages.Update(updateMessage); } }
/// <summary> /// Settingses the on command. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private void settingsOnCommand(object sender, ClientArgs e) { if (e.CommandID == (int)CommandEnum.GetConfigCommand) { setting = JsonConvert.DeserializeObject <Setting>(e.Args); OutPutDir = setting.OutPutDir; SourceName = setting.SourceName; LogName = setting.LogName; ThumbnailSize = setting.ThumbnailSize; HandlersArr = setting.ArrHandlers; } else if (e.CommandID == (int)CommandEnum.RemoveHandler) { //Application.Current.Dispatcher.Invoke(new Action(() => //{ HandlersArr.Remove(e.Args); //})); } }
/// <summary> /// Command settings /// </summary> /// <param name="sender">sender</param> /// <param name="e">args</param> private void settingsOnCommand(object sender, ClientArgs e) { //Checks if the id is get config if (e.CommandID == (int)CommandEnum.GetConfigCommand) { //Sets the settings, dir, sourcename and mroe the_settings = JsonConvert.DeserializeObject <Setting>(e.Args); SourceName = the_settings.SourceName; LogName = the_settings.LogName; OutPutDir = the_settings.OutPutDir; ThumbnailSize = the_settings.ThumbnailSize; HandlersArr = the_settings.ArrHandlers; } //Remove the data from hadnlers array else if (e.CommandID == (int)CommandEnum.RemoveHandler) { HandlersArr.Remove(e.Args); } }
/// <summary> /// 退出登录状态,但是不断开socket连接,如果需要断开连接,客户端发送'exit<EOF>'即可 /// </summary> /// <param name="eEvent"></param> private void ExeLogoutEvent(ClientEvent eEvent) { //Log Log.Info("thread" + Thread.CurrentThread.ManagedThreadId + " exe logout event", eEvent.Client.LogSource); //OP C_User cUser = ClientArgs.AnalysisBody <C_User>(eEvent.Body); //DB OP var result = DbUserAction.Logout(cUser.User_ID, eEvent.Client.Address.ToString(), eEvent.Client.Port); if (result.Status == DbEnum.Success) { //Log Log.Warn("update as Offline", eEvent.Client.LogSource); //status lock (eEvent.Client) { eEvent.Client.Login = false; } //Send Back if (eEvent.Client.Socket.Connected) { eEvent.Client.Send(NewEvent(Event_Type.Logout, result.Data).ToString()); } } else { //Log Log.Warn(result.Error, eEvent.Client.LogSource); //Send Error Back eEvent.Client.Send(NewEvent(Event_Type.Logout, new BadRequestArgs() { Code = result.ErrorCode, Message = result.Error }).ToString()); } }
public IEnumerable <ScriptDescriptor> GetScriptDescriptors() { var control = new ClientControl(); var res = new List <ScriptDescriptor>(); foreach (var extenderControl in _extenderControls) { if (extenderControl.Third != null && (!extenderControl.Third.Visible || IsExcluded(extenderControl.Third))) { continue; } if (extenderControl.Second == null) { /*if (!string.IsNullOrEmpty(extenderControl.First.TargetControlID)) * { * var enumerable = ((IExtenderControl)extenderControl.First).GetScriptDescriptors(control); * if (enumerable != null) res.AddRange(enumerable); * continue; * }*/ var clientArgs = new ClientArgs(); OnRetriveClientID(clientArgs); extenderControl.Second = clientArgs.ClientIDs; } var id = extenderControl.First.ID; extenderControl.First.Page = Page; extenderControl.First.SetTargetControl(this); foreach (var clientID in extenderControl.Second) { control.SetClientID(clientID); extenderControl.First.ID = id + clientID; var enumerable = ((IExtenderControl)extenderControl.First).GetScriptDescriptors(control); if (enumerable != null) { res.AddRange(enumerable); } } } return(res); }
private void ExeLoginEvent(ClientEvent eEvent) { //Log Log.Info("thread" + Thread.CurrentThread.ManagedThreadId + " exe login event", eEvent.Client.LogSource); //OP LoginArgs loginArgs = ClientArgs.AnalysisBody <LoginArgs>(eEvent.Body); //DB OP var result = DbUserAction.Login(loginArgs.Name, loginArgs.Password, eEvent.Client.Address.ToString(), eEvent.Client.Port); if (result.Data.Success) { lock (eEvent.Client) { eEvent.Client.Login = true; } eEvent.Client.Send(new ServerEvent() { Type = Event_Type.Login, RawContent = ClientArgs.ToBody(result.Data), SendTime = DateTime.Now.ToString() }.ToString()); } else { lock (eEvent.Client) { eEvent.Client.Login = false; } eEvent.Client.Send(new ServerEvent() { Type = Event_Type.Login, RawContent = ClientArgs.ToBody(new BadRequestArgs() { Code = result.ErrorCode, Message = result.Error }), SendTime = DateTime.Now.ToString() }.ToString()); } }
public SignalsConfig() { Port = 1978; HubHost = "localhost"; HubUri = "net.tcp://{0}:{1}/SignalsHub"; AgentUri = "net.tcp://{host}:{port}/SignalsHub/agent/{process}/{guid}"; ThrottledLogTtl = 15.Seconds(); TraceOn = false; Hub = new HubArgs { IdleSpan = 5.Seconds(), InactiveAgentTtl = 10.Seconds(), DeadAgentTtl = 30.Seconds(), DumpToLogPeriod = 1.Hours() }; Client = new ClientArgs { HelloMsgPeriod = 2.Seconds(), HelloMsgOnChangeSpan = 300.Milliseconds(), DumpToLogPeriod = 1.Hours(), IdleSpan = 20.Seconds(), HeartbeatSpan = 1.Minutes(), PublishRetryCount = 2 }; }
static ClientArgs ParseClientArgs(string[] args) { ClientArgs result = new ClientArgs(); string testType = args[2]; if (testType == "upload") { result.TestType = TestType.Upload; } else if (testType == "download") { result.TestType = TestType.Download; } else { result.TestType = TestType.Integrity; } result.ServerAddress = IPAddress.Parse(args[3]); result.ServerPort = Convert.ToInt32(args[4]); result.SizeInMb = Convert.ToInt32(args[5]); return(result); }
public static async Task <Client> Connect(CancellationToken token) { try { while (!token.IsCancellationRequested) { var clientProcess = await Client.GetLeagueClientProcess(token); var match = Client.InstallDirectoryRegex.Match(clientProcess.GetCommandLine()); var installDirectory = match.Groups["path"]; var lockfile = @"C:\Riot Games\League of Legends\lockfile"; Console.Write(installDirectory.ToString()); if (File.Exists(lockfile)) { string lockText; using (var lockfileStream = new FileStream( lockfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite )) { using (var textStream = new StreamReader(lockfileStream)) { lockText = await textStream.ReadToEndAsync(); } } var parts = lockText.Split(':'); var args = new ClientArgs { Process = parts[0], Pid = int.Parse(parts[1]), Port = ushort.Parse(parts[2]), Password = parts[3], Protocol = parts[4] }; var connectionString = $"127.0.0.1:{args.Port}/"; var client = new HttpClient { BaseAddress = new Uri($"{args.Protocol}://{connectionString}"), DefaultRequestHeaders = { { "Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"riot:{args.Password}"))}" } } }; var socket = new ClientWebSocket(); //서버 인증서 패스 System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; var uri = new Uri($"wss://{connectionString}"); socket.Options.UseDefaultCredentials = true; socket.Options.SetRequestHeader( "Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"riot:{args.Password}"))}" ); Console.Write(uri); await socket.ConnectAsync(uri, token); Console.WriteLine("Connected!"); return(new Client(client, socket, token)); } await Task.Delay(1000, token); } } catch (TaskCanceledException) { Console.WriteLine("Failed.."); return(null); } Console.WriteLine("."); return(null); }
private void newClientRequest(object a, ClientArgs e) { }
private static async Task Client_MessageDelete(Client client, ClientArgs <Message> args) { client.Logger.Log(LoggingLevel.Info, args.Data.Id.ToString()); }
private static async Task Client_MessageUpdate(Client client, ClientArgs <MessageUpdate> args) { //await args.Data.Message.Channel.Messages.Add("oi fdp"); }
private void newClientRequest(object a, ClientArgs e) { logs.addLogFromOutside(Constants.NEW_CLIENT_LOG + " NetworkNode", true, Constants.LOG_INFO); }
private static Task Client_GuildCreate(Client client, ClientArgs <Guild> args) { client.Logger.Log(LoggingLevel.Dcs, args.Data.Name); return(Task.CompletedTask); }
private async void Enviar_Click(object sender, RoutedEventArgs e) { try { CajaResultados.Document.Blocks.Clear(); bool formularioValido = ValidarFormulario(); if (formularioValido) { var usuario = CajaUsuario.Text; var password = CajaPassword.Password.ToString(); var tipo = CajaTipo.Text; var ruta = CajaRuta.Text; JustificacionFileType tipoJustificacion = JustificacionFileType.Bienes; switch (tipo) { case "Bienes": tipoJustificacion = JustificacionFileType.Bienes; break; case "Viajes": tipoJustificacion = JustificacionFileType.Viajes; break; case "Personal": tipoJustificacion = JustificacionFileType.Personal; break; default: CajaResultados.Document.Blocks.Add(new Paragraph(new Run("Debe seleccionar un tipo de justificante"))); break; } ClientArgs argumentos = new ClientArgs() { File = ruta, FileType = tipoJustificacion, Password = password, User = usuario }; CajaResultados.Document.Blocks.Add(new Paragraph(new Run("Procesando fichero..."))); Enviar.IsEnabled = false; // Se crea una tarea para ejecutar en un hilo distinto para evitar que se quede colgada la interfaz mientras se ejecuta Task tarea = Task.Run(() => { switch (argumentos.FileType) { case JustificacionFileType.Bienes: Process.ProcesarJustificantesBienesServicios(argumentos); break; case JustificacionFileType.Viajes: Process.ProcesarJustificantesViajes(argumentos); break; case JustificacionFileType.Personal: Process.ProcesarJustificantesPersonal(argumentos); break; default: throw new NotImplementedException(); } }); await tarea; } } catch (System.IO.FileNotFoundException ex) { CajaResultados.Document.Blocks.Add(new Paragraph(new Run(ex.Message))); } catch (Exception ex) { CajaResultados.Document.Blocks.Add(new Paragraph(new Run(ex.Message))); } finally { Enviar.IsEnabled = true; } }
private static Task Client_Ready(Client client, ClientArgs <Ready> args) { return(Task.CompletedTask); }