asyncsocket java_Netty实现的一个异步Socket代码

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

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值