Netty实现的一个异步Socket代码
本人写的一个使用Netty实现的一个异步Socket代码
package test.core.nio; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /**
* @author xfyou
* @date 2019/3/21
*/
@Slf4j
public class AsyncSocket { private final ClientBootstrap clientBootstrap; private final InetSocketAddress address; private int timeout; private static final byte CONNECTORS_POOL_SIZE = 1; private static final byte WORKERS_POOL_SIZE = 30; public AsyncSocket(String hostIp, String port, int timeout, 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<Runnable>(), threadFactory);
final ExecutorService workers = new ThreadPoolExecutor(WORKERS_POOL_SIZE, WORKERS_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(connectors, workers, CONNECTORS_POOL_SIZE, WORKERS_POOL_SIZE));
address = new InetSocketAddress(hostIp, NumberUtils.toInt(port));
clientBootstrap.setOption("remoteAddress", address);
clientBootstrap.setOption("connectTimeoutMillis", timeout);
this.timeout = timeout;
addShutdownHook();
} @SneakyThrows
public byte[] send(final byte[] data) {
final SocketEventHandler socketEventHandler = new SocketEventHandler(timeout);
final Channel channel = clientBootstrap.getFactory().newChannel(Channels.pipeline(socketEventHandler));
final ChannelFuture future = channel.connect(address);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
channel.write(ChannelBuffers.wrappedBuffer(data));
} else {
log.error("I/O operation has failed.", future.getCause());
throw (Exception) future.getCause();
}
}
});
return socketEventHandler.getMessage();
} private void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
clientBootstrap.releaseExternalResources();
}
});
} private class SocketEventHandler extends SimpleChannelUpstreamHandler { private byte[] message; private int timeout; private final CountDownLatch latch = new CountDownLatch(1); SocketEventHandler(int timeout) {
this.timeout = timeout;
} @SneakyThrows
byte[] getMessage() {
latch.await(timeout, TimeUnit.MILLISECONDS);
return message;
} @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
if (null != e.getMessage()) {
message = ((ChannelBuffer) e.getMessage()).array();
latch.countDown();
}
if (null != ctx.getChannel()) {
ctx.getChannel().close();
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
if (null != ctx.getChannel()) {
ctx.getChannel().close();
}
log.error("An exception was raised by an I/O thread.", e.getCause());
} } }
Netty实现的一个异步Socket代码的更多相关文章
- Netty接收到一个请求但是代码段执行了两次
这是因为HttpRequestDecoder把请求拆分成HttpRequest和HttpContent两部分, 所以在建立连接的时候建立了两次.
- 一个高性能异步socket封装库的实现思路 (c#)
前言 socket是软件之间通讯最常用的一种方式.c#实现socket通讯有很多中方法,其中效率最高就是异步通讯. 异步通讯实际是利用windows完成端口(IOCP)来处理的,关于完成端口实现原理, ...
- ES transport client底层是netty实现,netty本质上是异步方式,但是netty自身可以使用sync或者await(future超时机制)来实现类似同步调用!因此,ES transport client可以同步调用也可以异步(不过底层的socket必然是异步实现)
ES transport client底层是netty实现,netty本质上是异步方式,但是netty自身可以使用sync或者await(future超时机制)来实现类似同步调用! 因此,ES tra ...
- Netty(1):第一个netty程序
为什么选择Netty netty是业界最流行的NIO框架之一,它的健壮型,功能,性能,可定制性和可扩展性都是首屈一指的,Hadoop的RPC框架Avro就使用了netty作为底层的通信框架,此外net ...
- 简单的异步Socket实现——SimpleSocket_V1.1
简单的异步Socket实现——SimpleSocket_V1.1 笔者在前段时间的博客中分享了一段简单的异步.net的Socket实现.由于是笔者自己测试使用的.写的很粗糙.很简陋.于是花了点时间自己 ...
- Python简易聊天工具-基于异步Socket通信
继续学习Python中,最近看书<Python基础教程>中的虚拟茶话会项目,觉得很有意思,自己敲了一遍,受益匪浅,同时记录一下. 主要用到异步socket服务客户端和服务器模块asynco ...
- 项目笔记---C#异步Socket示例
概要 在C#领域或者说.net通信领域中有着众多的解决方案,WCF,HttpRequest,WebAPI,Remoting,socket等技术.这些技术都有着自己擅长的领域,或者被合并或者仍然应用于某 ...
- 深入理解Tornado——一个异步web服务器
本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html原 ...
- 可扩展多线程异步Socket服务器框架EMTASS 2.0 续
转载自Csdn:http://blog.csdn.net/hulihui/article/details/3158613 (原创文章,转载请注明来源:http://blog.csdn.net/huli ...
随机推荐
- Hadoop |集群的搭建
Hadoop组成 HDFS(Hadoop Distributed File System)架构概述 NameNode目录--主刀医生(nn): DataNode(dn)数据: Secondary N ...
- Python中GIL
GIL(global interpreter lock)全局解释器锁 python中GIL使得同一个时刻只有一个线程在一个cpu上执行,无法将多个线程映射到多个cpu上执行,但GIL并不会一直占有,它 ...
- 进程篇:wait & waitpid
#include <sys/types.h> /* 提供类型pid_t的定义 */ #include <sys/wait.h> pid_t wait(int *status) ...
- python基础一 ------如何统计一个列表元素的频度
如何统计一个列表元素的频度 两个需求: 1,统计一个随机序列[1,2,3,4,5,6...]中的出现次数前三的元素及其次数 2,统计一片英文文章中出现次数前10 的单词 两种方法: 1,普通的for循 ...
- [CF575B]Bribes
[CF575B]Bribes 题目大意: 一棵\(n(n\le10^5)\)个结点的树,有些边有方向,对于每条边,如果第\(i\)次逆向走过这条边,就会产生\(2^{i-1}\)的代价.开始在\(1\ ...
- error :expected initializer before
很可能头文件或者前面的某个定义少了个:
- sqlserver的like '%xxx%'优化,全文索引
2000万行的数据表,首先对Address字段做'%xxx%'模糊查询 这是估计的查询计划 这是估计的实际查询结果,用了37秒才查询完成 还是之前的数据,但是这一次使用'xxx%'来做查询,现在还没有 ...
- 配置魔药 [NOIP模拟] [DP] [费用流]
问题描述在<Harry Potter and the Chamber of Secrets>中,Ron 的魔杖因为坐他老爸的 Flying Car 撞到了打人柳,不幸被打断了,从此之后,他 ...
- 搭建TFS 2015 Build Agent环境(四)
在通过TFS做DI时,我们经常用到FTP文件上传.TFS发布中,提供了cURL上载文件功能.要想使用此功能,请参考下面步骤启用: 1.登录BuildAgent所在的机器 2.打开cmd(以管理员权限运 ...
- yii2 创建模块modules
方案一:如果模块儿较少,不用专门给模块儿目录定义别名,酱紫做就ok啦. 1.在项目根目录下面创建一个 modules 目录. 2.进入 gii : http://localhost/basic/web ...