How to handle events in C #

1

Using the "TcpListener" class I'm "listening" for a port where multiple clients will connect. So peaceful. In order to receive data from a client I used a Thread that generates an event whenever any data is received. However when creating the event I can not get an idea of how to know which event belongs to which client. Note: clients are in a List.

    private async void btnAceitarClientes_Click(object sender, EventArgs e)
    {
        if (ServerTCP.Started)
        {
            await ServerTCP.AddAllPendingClients();

            if (ServerTCP.clientList.Count > 0)
            {
                for (int i = 0; i < ServerTCP.clientList.Count; i++)
                {
                    if (ServerTCP.clientList[i].Connected)
                    {
                        Log.print(richTextBox1, Log.tipo.Controlador, string.Format("\r\nIP Conectado : {0}", ServerTCP.clientList[i].IP));

                        //Gera evento de recepçao.
                        ServerTCP.clientList[i].DataReceivedInBackGround += FrmControllers_Conector_DataReceivedInBackGround;

                    }
                    else
                    {
                        Log.print(richTextBox1, Log.tipo.Controlador, "\r\nCliente aceito mas não conectado.");
                    }
                }
            }
            else
            {
                Log.print(richTextBox1, Log.tipo.Controlador, "\r\nNão há clientes na lista.");
            }
        }
    }

    private void FrmControllers_Conector_DataReceivedInBackGround(object source, EventArgs e)
    {

        Log.print(richTextBox1, Log.tipo.Controlador, ServerTCP.clientList[QUAL CLIENTE É ESTE???].Read());

    }
    
asked by anonymous 08.03.2018 / 19:46

1 answer

0

Resolved:

    private void FrmControllers_Conector_DataReceivedInBackGround(object source, EventArgs e)
    {
        //Identifico o index do cliente que chamou o evento na lista de clients
        int i = ServerTCP.clientList.FindIndex(source.Equals);
        //Printo no log o IP e a Mensagem recebida.
        Log.print(richTextBox1, Log.tipo.Controlador, string.Format("[{0}] : {1} ", ServerTCP.clientList[i].IP, ServerTCP.clientList[i].Read()));
    }
    
08.03.2018 / 20:11