与Netty聊天服务器

时间:2012-12-04 05:43:17

标签: java networking netty

我和netty写了一个简单的聊天服务器,朋友和我一直用telnet测试它。当我们两个都连接时,它表示组的大小是1.每当写入用户列表时,它只会写入发送消息的人。我怎样才能解决这个问题?

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());
  }


}

1 个答案:

答案 0 :(得分:2)

您必须为所有创建的ChannelPipeline实例共享同一个处理程序实例。或者将ChannelGroup声明为静态最终