Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411423 Posts in 69363 Topics- by 58416 Members - Latest Member: JamesAGreen

April 18, 2024, 11:51:29 PM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)Retrieving the list of clients from the c++ socket
Pages: [1]
Print
Author Topic: Retrieving the list of clients from the c++ socket  (Read 524 times)
mymot
Level 0
*


View Profile
« on: May 07, 2018, 09:44:32 AM »

I have a question about downloading the list of connected clients of the c++ sockets, how to send the first connected client information about the other one who connected right after it?
the first client connects, writes the socket to std::vector <int> connection using connection.push_back (socket)
starts a thread, then it increases by one int clients. When the second client connects, puts socket into the vector, runs the thread, increases clients++ and has all the information about the first client, and the client first has no information about the second client, the vector connection does not change, nor does the clients increase.
The second client can send the message to himself and the client first using the for loop (int i = 0; i <clients + 1; i ++) send ("message"), but the client can only do the same for himself, how to deal with it?

global variables:
   std::vector <int> connection;
   int clients;

code:
   size = sizeof(client_addr);
   client = accept( server, ( struct sockaddr * ) & client_addr, & size );
   connection.push_back(client);
   //thread
   if(!fork())
   {
      Client hClient;
      hClient.Thread();
   }
   //thread
   clients++;   
Logged
shay
Level 0
**


View Profile
« Reply #1 on: May 14, 2018, 04:03:46 AM »

If I understand your code snippet correctly, you're using a class as your server, to register all clients, supplying a separate thread for each client's connection.
If that's the case - theoretically, there's no issue - both the vector of connections, and the int clients, are shared across all threads - so all threads should be able to loop through all connections and send messages to all of them.
That being said, your code is *extremely* not thread-safe, and you're heading for a world of pain when trying to debug real-world multi-player issues. I would recommend reading a bit about concurrency and multi-threading in C++ before diving into that complicated area.
If you post all of your code, instead of a snippet, we can have a look, and offer proper fixes (stackoverflow style).
Logged
Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic