1
votes

I need some advice how to implement a netty server which gets data from some source(files for example) and then sends it as strings to all connected clients. I'd like to have class Server and invoke method broadcast on an object of this class. It should be used like this:

Server server = new Server();
String message;

while (true) {
    message = getMessage();
    server.broadcast(message);
}

I know that for this purpose I can use ChannelGroup however I don't know how to prevent channel write buffer from being exceeded (I don't know how to use channel.isWritable()).

ChannelGroup broadcast = new DefaultChannelGroup("broadcast");

...

public void broadcast(String message) {
    for (Channel channel : broadcast) {
        if (channel.isWritable())
            channel.write(message);
    }
}

Above solution is wrong because I want each message to be delivered to each client. I'd appreciate some advice how to solve my problem.

1

1 Answers

1
votes

If by delivered to each client you mean that you need to send it to each client, then the easiest technique is to use the methods on ChannelGroup itself. The writeAndFlush method (write method if netty 3.x) returns a future that will be signalled when the message has been flushed to all channels in the group.

ChannelGroupFuture future = broadcast.writeAndFlush(message);
future.awaitUninterruptibly();

You can use the methods of ChannelGroupFuture to determine if the message was written all channels, and to figure out which channels failed.

This will limit you to the performance of the slowest channel but your example code implies that's ok. Having individual channels run at full speed, or knowing the message was actually delivered, increases the scope dramatically.