How to control events in C#

Asked

Viewed 70 times

1

Using the "Tcplistener" class I am "listening" to a port where several customers will connect. Until then quiet. To receive data from a client I used a Thread that generates an event whenever some data is received. But when creating the event I cannot 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());

    }
  • Usually this information comes in the eventargs...

  • I tried to do something like:" int i = Servertcp.clientList.Findindex(e.XXXXX); "but I don’t know how.

  • Good afternoon! Analyzing your need, I see that maybe the ideal would be you work with Signalr, is a socket C#, very good, with it you can know which users are connected. Sending a message to a specific user, group of users or all users. is very easy to use. I always point out this article from Eduardo Pires site, it is practical and easy to teach, I learned from him. Today I use in all my projects. http://www.eduardopires.net.br/2013/04/aspnet-signalr-introducao-e-utilizacao/

1 answer

0

Solved:

    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()));
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.