Example #1
0
        //this function is handeling the client
        public void HandleClient(TcpClient client)
        {
            NetworkStream stream = client.GetStream();
            BinaryReader  reader = new BinaryReader(stream);
            BinaryWriter  writer = new BinaryWriter(stream);

            //creates a new task to listen to the client's requests
            new Task(() =>
            {
                this.writers.Add(writer);
                string commandLine = reader.ReadString();
                bool result;
                JsonCommand command = JsonConvertor.GenerateJsonCommandObject(commandLine);

                try
                {
                    while (command.CommandID != (int)CommandsEnum.CloseCommand)
                    {
                        string message   = this.controller.ExecuteCommand(command.CommandID, command.Args, out result);
                        command.JsonData = message;
                        command.Result   = result;
                        writer.Write(JsonConvertor.GenerateJsonCommandString(command));

                        commandLine = reader.ReadString();
                        command     = JsonConvertor.GenerateJsonCommandObject(commandLine);
                    }
                }
                catch (Exception e)
                {
                    this.writers.Remove(writer);
                    return;
                }
                this.writers.Remove(writer);
                client.Close();
            }).Start();
        }
        //the function connects the client to the server
        //it creates a new thread to receieve commands constently and invoke commandReceived
        public void ConnectToServer()
        {
            client.Connect(ep);
            NetworkStream stream = client.GetStream();

            this.reader = new BinaryReader(stream);
            this.writer = new BinaryWriter(stream);

            Task task = new Task(() =>
            {
                try
                {
                    this.connected = true;
                    while (true)
                    {
                        string output = this.reader.ReadString();
                        this.CommandReceived?.Invoke(this, new CommandReceivedEventArgs(JsonConvertor.GenerateJsonCommandObject(output)));
                    }
                }
                catch (Exception e)
                {
                    this.connected = false;
                }
            });

            task.Start();
        }