c++socketsclient-serversockaddr-in

C++ [UDP] How to keep track of all connected(clients) socket connections on server?


my server should forward the message it received to all connected clients but my code can only send the message back to the sender.

struct User
{
    char user_id[20];
    string address;
    struct sockaddr_in CONNECTED;
}U[8];

//USER LOGIN
    for(int i = 0; i < 8; i++)
    {
        //DO THIS WHEN USER MATCHED
        //user_id consists of Andrew, Lisa, David and etc
        //so that each unique name has a unique connection(CONNECTED)
        if(strcmp(user_id,U[i].user_id) == 0)
        {
            U[i].CONNECTED = cln_addr;
        }

    }

        //AFTER RECEIVING THE MESSAGE FROM CLIENT, SEND THE MESSAGE BACK TO ALL CONNECTED CLIENTS
        for(int i = 0; i < 8; i++)
    {
        sendto (*csock, BROADCASTMESSAGE, sizeof BROADCASTMESSAGE, 0, (struct sockaddr *)&U[i].CONNECTED, len_c_addr); //THIS HOWEVER ONLY FORWARD MESSAGE BACK TO THE SENDER
    }

Solution

  • when you accept a socket in server socket,store it on an array list .when that client gone,remove it from your array.

    with this array you can send and broadcast data to your active clients.