I have to implement a multithreaded broadcast chat server in c++ (for school project). I cannot use async socket and I'm writing it in C++ under Win32 (boost-based solution will be ok).
My design should be quite simple and straightforward: a "main" thread wait for incoming connection and, when a new connection arrives, it pass it to a (new) thread in the thread pool (legacy API) for reading messages from the client.
Here it comes the first problem: (A) should I pass the socket to another (new) thread for writing to the client? Or (B) should I use the same thread for reading-writing? Or (C) should I use a unique thread for writing to all clients? (again, synchronously).
If I go for solution A or B, when a message arrives from a client it should be somehow dispatched to all other connected clients: should I put it in a single (shared) variable and use some sync construct to have all thread waiting for it? It's should be something like reader/writer + barrier (dynamic size), I guess, but I didn't managed to work this out.
On the other end, if I go for solution C, I have to iterate somehow on a collection (e.g. an st::list) of 'socket' or a collection of 'subscriber object' or something like that. In that case my main concern is about how manage cancellation from collection (and parallel reading from it, of course). A possible solution would be to lock the whole collection with the same mutex....but I don't think it will work well.
I don't want you to solve the problem for me, of course, but if you can point me out some pattern that can fit my problem or some solution to similar problem it would be perfect. (Anyway, the main issue here is the broadcast!)
Thanks
The main questions to ask yourself in solving this assignment have to do with SCALE, and RESPONSIVENESS. Those answers will help determine the architecture needed to meet the requirements.
The Reactor Pattern most closely fits what you've outlined so far, and meshes well with boost::asio. http://en.wikipedia.org/wiki/Reactor_pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With