3

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
    }
Lozy
  • 160
  • 4
  • 11

1 Answers1

3

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.

  • Mind explaining why I am not getting the right result despite my way of doing it is the same as your answer ? – Lozy Jun 23 '16 at 07:44
  • @Lozy No it isn't. You are always sending on the same socket. – user207421 Jun 23 '16 at 07:57
  • 1
    @EJP how do I store a list of connected(clients) connections then, in order to broadcast the message. One of the vague answers given on another thread with the same goal was "keep track of the connections" Which I believe I know what it meant, I just have to iterate the connections through my last for loop in the code above. Since you said that all sockets are all the same, what would be the unique variable that distinguish the clients ? – Lozy Jun 23 '16 at 08:03
  • @EJP he's using sendto, which implies UDP or some other connectionless protocol – Richard Hodges Jun 23 '16 at 08:04
  • @RichardHodges He is talking about 'connected clients', which implies TCP. – user207421 Jun 23 '16 at 23:30
  • @Lozy In a data structure. – user207421 Jun 23 '16 at 23:30