1

I am working on a broadcast server where all clients should be able to send a broadcast message to all clients, and all clients should receive a broadcast from any client. I'm trying to figure out what the best way would be to implement this on the server side. I've run across a BlockingQueue, but my understanding is that when one thread calls take(), it removes the item so that the other threads can't get the data, and that each client is either a producer or a consumer. What would the best way be to implement this? Each client will have a thread on the server side.

Thanks!

Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
user2078519
  • 135
  • 2
  • 12
  • possible duplicate of [Producer/Consumer threads using a Queue](http://stackoverflow.com/questions/2332537/producer-consumer-threads-using-a-queue) – Jared Burrows Mar 03 '14 at 21:18

4 Answers4

0

You need some kind of pub-sub mechanism. This is hard to implement in Java from the bottom up. I recommend you look at some existing implementation.

For a simple, non persistent solution you should check out the Guava EventBus. Spring has something like an event bus according to this SO, although I can't find more docs. Finally you can check out the Akka event bus if you're feeling adventurous.

For a persistent solution you could use a JMS provider (like ActiveMQ) and the topic/subscriber pattern. I've had very good experiences with Spring + JMS. Redis can also do pub/sub (not a JMS implementation!) and it has the advantage of being distributed. I've never tried it so I don't know how good it is.

Community
  • 1
  • 1
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
0

Give each client a thread-safe queue, and insert sent all messages into every queue.

When no client needs a message any more, it will be automatically garbage collected.

Kent
  • 713
  • 2
  • 8
  • 19
  • After writing that, it seems really inefficient. I guess that's what you get when using broadcast messages. – Kent Mar 03 '14 at 21:23
0

This is a tricky subject and I really do not recommend rolling your own. Use ActiveMQ or RabbitMQ instead. These people work on this all day long and know what they are doing.

ced-b
  • 3,957
  • 1
  • 27
  • 39
0

Take a look for kryonet project. I'm using it in my few projects and it's realy good