我想验证服务器仅看到我在netty客户端固定池中设置的连接数 这是我为净值4.1.12.Final设置的。我一直在服务器端看到很多连接,不确定发生了什么。我在服务器处理程序中使用计数器来跟踪建立的连接。
服务器
package com.venu;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HelloServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 9999;
}
new NettyServer(port).run();
}
}
服务器处理程序
package com.venu;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
public class HelloServerHandler extends ChannelInboundHandlerAdapter {
private static int counter = 0;
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
System.out.println("Established connection: ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server received: ");
ByteBuf inBuffer = (ByteBuf) msg;
String received = inBuffer.toString(CharsetUtil.UTF_8);
System.out.println("Server received: " + received);
Thread.sleep(5000);
ctx.writeAndFlush(Unpooled.copiedBuffer("Hello venu" + received, CharsetUtil.UTF_8));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println(" channel read complete " );
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
decrement();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
public void channelActive(ChannelHandlerContext ctx)
throws java.lang.Exception {
increment();
System.out.println(" channel activated counter is " + getCount() );
}
private synchronized int getCount() {
return counter;
}
private synchronized void increment() {
counter++;
}
private synchronized void decrement() {
counter--;
}
}
客户
package com.venu;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.pool.FixedChannelPool;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
public class NettyClient {
private static boolean initialized = false;
public NettyClient() {
System.out.println("Called netty client");
}
private static FixedChannelPool fcp;
public static void initialize() {
if ( !initialized ) {
EventLoopGroup group = new NioEventLoopGroup();
final Bootstrap cb = new Bootstrap();
cb.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ClientHandler());
}
});
cb.remoteAddress("localhost", 9999);
cb.group(group).channel(NioSocketChannel.class);
fcp = new FixedChannelPool(cb, new ChannelPoolHandler(), 2, 30000);
initialized = true;
}
else {
System.out.println("already initialized");
}
}
public static void getClientHandler() {
initialize();
try {
Future<Channel> f = fcp.acquire();
Channel c = f.get();
ClientHandler ch = (ClientHandler) c.pipeline().last();
System.out.println("Fetched " + ch.getFactorial());
fcp.release(c);
}
catch (Exception e){}
}
}
客户端处理程序
package com.venu;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ClientHandler extends SimpleChannelInboundHandler {
final BlockingQueue<String> answer = new LinkedBlockingQueue<String>();
public String getFactorial() {
boolean interrupted = false;
try {
for (;;) {
try {
return answer.take();
} catch (InterruptedException ignore) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
public ClientHandler(){
System.out.println("INstantiated client handler");
}
@Override
public void channelActive(ChannelHandlerContext channelHandlerContext){
System.out.println("Cient channel active called " ) ;
channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("Netty Rocks!", CharsetUtil.UTF_8));
}
public void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) {
System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause){
cause.printStackTrace();
channelHandlerContext.close();
}
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
ByteBuf inBuffer = (ByteBuf) o;
String received = inBuffer.toString(CharsetUtil.UTF_8);
System.out.println("Clinet channel read 0 received: " + received);
answer.add(received);
}
}
测试器
package com.venu;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadSend {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(20);
for (int i= 0; i< 2000; i++) {
es.submit(new CallableClient());
}
es.shutdown();
}
}
可调用对象
package com.venu;
import java.util.concurrent.Callable;
public class CallableClient implements Callable {
public Object call() {
NettyClient.getClientHandler();
return null;
}
}