packagetest.core.nio;importcom.google.common.util.concurrent.ThreadFactoryBuilder;importjava.net.InetSocketAddress;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.LinkedBlockingQueue;importjava.util.concurrent.ThreadFactory;importjava.util.concurrent.ThreadPoolExecutor;importjava.util.concurrent.TimeUnit;importlombok.SneakyThrows;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.lang3.math.NumberUtils;importorg.jboss.netty.bootstrap.ClientBootstrap;importorg.jboss.netty.buffer.ChannelBuffer;importorg.jboss.netty.buffer.ChannelBuffers;importorg.jboss.netty.channel.Channel;importorg.jboss.netty.channel.ChannelFuture;importorg.jboss.netty.channel.ChannelFutureListener;importorg.jboss.netty.channel.ChannelHandlerContext;importorg.jboss.netty.channel.Channels;importorg.jboss.netty.channel.ExceptionEvent;importorg.jboss.netty.channel.MessageEvent;importorg.jboss.netty.channel.SimpleChannelUpstreamHandler;importorg.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;/***@authorxfyou
* @date 2019/3/21*/@Slf4jpublic classAsyncSocket {private finalClientBootstrap clientBootstrap;private finalInetSocketAddress address;private inttimeout;private static final byte CONNECTORS_POOL_SIZE = 1;private static final byte WORKERS_POOL_SIZE = 30;public AsyncSocket(String hostIp, String port, inttimeout, String name) {final ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(name + "-pool-%d").setPriority(Thread.NORM_PRIORITY).build();final ExecutorService connectors = new ThreadPoolExecutor(CONNECTORS_POOL_SIZE, CONNECTORS_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), threadFactory);final ExecutorService workers = new ThreadPoolExecutor(WORKERS_POOL_SIZE, WORKERS_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), threadFactory);
clientBootstrap= new ClientBootstrap(newNioClientSocketChannelFactory(connectors, workers, CONNECTORS_POOL_SIZE, WORKERS_POOL_SIZE));
address= newInetSocketAddress(hostIp, NumberUtils.toInt(port));
clientBootstrap.setOption("remoteAddress", address);
clientBootstrap.setOption("connectTimeoutMillis", timeout);this.timeout =timeout;
addShutdownHook();
}
@SneakyThrowspublic byte[] send(final byte[] data) {final SocketEventHandler socketEventHandler = newSocketEventHandler(timeout);final Channel channel =clientBootstrap.getFactory().newChannel(Channels.pipeline(socketEventHandler));final ChannelFuture future =channel.connect(address);
future.addListener(newChannelFutureListener() {
@Overridepublic void operationComplete(ChannelFuture future) throwsException {if(future.isSuccess()) {
channel.write(ChannelBuffers.wrappedBuffer(data));
}else{
log.error("I/O operation has failed.", future.getCause());throw(Exception) future.getCause();
}
}
});returnsocketEventHandler.getMessage();
}private voidaddShutdownHook() {
Runtime.getRuntime().addShutdownHook(newThread() {
@Overridepublic voidrun() {
clientBootstrap.releaseExternalResources();
}
});
}private class SocketEventHandler extendsSimpleChannelUpstreamHandler {private byte[] message;private inttimeout;private final CountDownLatch latch = new CountDownLatch(1);
SocketEventHandler(inttimeout) {this.timeout =timeout;
}
@SneakyThrowsbyte[] getMessage() {
latch.await(timeout, TimeUnit.MILLISECONDS);returnmessage;
}
@Overridepublic voidmessageReceived(ChannelHandlerContext ctx, MessageEvent e) {if (null !=e.getMessage()) {
message=((ChannelBuffer) e.getMessage()).array();
latch.countDown();
}if (null !=ctx.getChannel()) {
ctx.getChannel().close();
}
}
@Overridepublic voidexceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {if (null !=ctx.getChannel()) {
ctx.getChannel().close();
}
log.error("An exception was raised by an I/O thread.", e.getCause());
}
}
}