I need to track individual client's connections (written, read bytes and speed(bytes per second)) in my simple http server netty app. As I understand, to do this, I have to use ChannelTrafficShapingHandler
.
What methods must be overriden and how can I do these calculations?
My ChannelInitializer:
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec", new HttpServerCodec())
.addLast("traffic", new TrafficShapingHandler(AbstractTrafficShapingHandler.DEFAULT_CHECK_INTERVAL))
.addLast("handler", new HttpServerHandler());
}
}
My SimpleChannelInboundHandler:
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpRequest> {
private static DefaultChannelGroup activeChannels = new DefaultChannelGroup("netty-receiver", ImmediateEventExecutor.INSTANCE);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
activeChannels.add(ctx.channel());
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
if (is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
String uri = req.getUri().toLowerCase();
Controller controller = ControllerFactory.getController(uri);
FullHttpResponse response = controller.getResponse();
if (controller instanceof HelloController) {
ctx.executor().schedule(() -> ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE), 3, TimeUnit.SECONDS);
} else {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
public static long getConnectionsQuantity() {
return activeChannels.size();
}
}