public void ReadMesagge() { new Task(() => { try { string arg; stream = this.client.GetStream(); BinaryReader reader = new BinaryReader(stream); while (client.Connected) { arg = reader.ReadString(); CommandRecievedEventArgs e = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(arg); //if (e.CommandID == (int)CommandEnum.ExitCommand) //{ // // Client want to exit. // break; //} OnCommandRecieved?.Invoke(this, e); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Close(); } }).Start(); }
private Task HandleConnectionAsync(TcpClient client) { return(Task.Run(async() => { using (NetworkStream stream = client.GetStream()) { bool running = true; BinaryReader reader = new BinaryReader(stream); string msg = string.Empty; SetConfigsAndLogs(client); while (running) { try { msg = reader.ReadString(); Console.WriteLine("msg: {0}", msg); CommandRecievedEventArgs cmd = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(msg); Console.WriteLine("command is: {0}", cmd); // client exit if (cmd.CommandID == (int)CommandEnum.ExitCommand) { client.Close(); clients.Remove(client); Console.WriteLine("Client removed"); break; } OnCommandRecieved?.Invoke(this, cmd); } catch (Exception ex) { running = false; clients.Remove(client); Console.WriteLine(ex.Message); } } Console.WriteLine("closing client"); } })); }