0

Ii have a server in c (winsock) for multiple connections using ThreadCreate() and i store all the new client sockets in an array. Handle peers[10]. By now when i receive data from 1 peer i only loop throug the array and send the data on every socket. But now i face 2 problems

  1. when a new peer connects i just count up an integer, but when it closes the connection i must reorder the HANDLE array to not get over MAX_CONNECTIONS very early

  2. When (later on) i want send data to a specific socket i need something like a numbering system

My questions:

  1. What is the best way to solve problem 1? the ordering when connections starts/stops

  2. Is it ok to just associate every peer with an integer and select it based on that or maybe its ip?

Thanks

DoJo
  • 45
  • 9
  • 1
    One common way is to not use arrays but lists or other container data types. Another simple way (using an array) is to use `INVALID_SOCKET` for sockets that are not used, and then loop over the whole array checking for valid sockets when needed. – Some programmer dude Dec 25 '18 at 19:45
  • Check this [DEMO](https://pastebin.com/raw/ZqMT7Spp) how to handle those connections. – Michi Dec 25 '18 at 20:01
  • When a client connects, the server gets a socket number (typically returned from the `accept()` statement) That socket number (doesn't matter if it is 'ordered' or not) is what is needed to communicate with that client. In general, have a separate thread for each client. The thread handles ALL the communication with that client. When the client disconnects, then just kill that thread. Then no need to track all the connections. – user3629249 Dec 26 '18 at 00:03
  • BTW: since starting and killing a thread takes a lot of time, May I suggest using a [thread pool](http://faculty.washington.edu/jstraub/isilon/isilon2/Unit7/threadpool/doc/html/example_8c-example.html) – user3629249 Dec 26 '18 at 00:03
  • please post a [mcve] so we can reproduce the problem thereby we can help you debug it – user3629249 Dec 26 '18 at 00:14
  • I'm thinking we have all said: Do not number the clients, rather, just use the `socket` associated with that client. – user3629249 Dec 27 '18 at 01:03
  • If you just wanted an opinion: stackoverflow is NOT the place to post the question. – user3629249 Dec 27 '18 at 01:23
  • My bad, to be honest i tried to get an opinion including an example. – DoJo Dec 27 '18 at 02:41

0 Answers0