Reputation: 45
I wrote a simple chat server with netty, a friend and I have been testing it with telnet. When both of us are connected, it says the size of the group is 1. Whenever writing to the list of users, it only writes to whoever sent the message. How can I fix this?
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
public class ServerChannelHandler extends SimpleChannelHandler {
private ChannelGroup users = new DefaultChannelGroup();
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
users.write(e.getMessage());
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
users.add(e.getChannel());
System.out.println("Opened. ");
System.out.println(users.size());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
users.remove(e.getChannel());
}
}
Upvotes: 1
Views: 1003
Reputation: 23557
you must share the same instance of the handler for all created ChannelPipeline instances. Or declare the ChannelGroup as static final
Upvotes: 2