2015-06-18 17:59:14.0|分类: NIO|浏览量: 9912
|
服务器端需要做一些日志监控,需要查看服务器端当前有多少客户端连接。 查看了netty的一些资料和博客信息,没有发现官方提供一些直接方法。 最后只能自己做一些处理了。在启动服务器的时候需要设置channelFactory。 ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.channelFactory(new NettyServerChannelFactory<ServerChannel>(NioServerSocketChannel.class))
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new NettyMessageDecoder());
socketChannel.pipeline().addLast(new NettyMessageEncoder());
socketChannel.pipeline().addLast("IdleStateHandler",
new IdleStateHandler(60, 20, 10));
socketChannel.pipeline().addLast(new NettyChannelHandlerAdapter(connectManager));
socketChannel.pipeline().addLast("IdlChannelHandlerAdapter",
new IdlChannelHandlerAdapter());
}
});
System.err.println(" 绑定端口>>"+SERVER_ADDR+":"+PORT);channel工厂,进行channel的生产。在这个工厂内进行处理channel的管理。 import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import io.netty.bootstrap.ServerChannelFactory;
import io.netty.channel.ChannelException;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.util.internal.StringUtil;
public class NettyServerChannelFactory implements ServerChannelFactory {
private List listServerChannel = new ArrayList();
private final Class clazz;
NettyServerChannelFactory(Class clazz) {
this.clazz = clazz;
}
@Override
public T newChannel(EventLoop eventLoop, EventLoopGroup childGroup) {
try {
Constructor constructor = clazz.getConstructor(EventLoop.class, EventLoopGroup.class);
T t = constructor.newInstance(eventLoop, childGroup);
listServerChannel.add(t);
return t;
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + clazz, t);
}
}
public int getListServerChannelSize(){
return listServerChannel.size();
}
public List getListServerChannel() {
return listServerChannel;
}
@Override
public String toString() {
return StringUtil.simpleClassName(clazz) + ".class";
}
}自定义了一个list,把创建的channel都放到list中,然后获取list的大小。 现在这个方法有一个问题,channel关闭之后应该删除掉,需要改进。 mina和netty很像。mina提供了获取所有链接的方法 NioSocketAcceptor中getManagedSessionCount() |
