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 ...
随机推荐
- 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
从第0行开始,输出第k行,传的参数为第几行,所以在方法中先将所传参数加1,然后将最后一行加入集合中返回. 代码如下: public static List<Integer> generat ...
- HashMap实现原理简析及实现的demo(一看就明白)
HashMap底层就是一个数组结构,数组中的每一项又是一个链表. jdk源码: transient Node<K,V>[] table; static class Node<K,V& ...
- thinkphp5控制器
// 定义应用目录 define('APP_PATH', __DIR__ . '/../app/'); // 定义配置文件目录和应用目录同级 define('CONF_PATH', __DIR__.' ...
- 富文本编辑器上传图片需要配置js,后台代码
富文本编辑器上传图片需要配置js,后台代码
- JavaEE 之 WebService
1.WebService a.定义:WebService是一种跨编程语言和跨操作系统平台的远程调用技术 b.三大技术: XML+XSD,SOAP,WSDL c.SOAP协议 = HTTP协议 + XM ...
- SVM—PK—BP:SVR(better)和BP两种方法比较且实现建筑物钢筋混凝土抗压强度预测—Jason niu
load concrete_data.mat n = randperm(size(attributes,2)); p_train = attributes(:,n(1:80))'; t_train = ...
- POJ 3177 Redundant Paths (边双连通+缩点)
<题目链接> <转载于 >>> > 题目大意: 有n个牧场,Bessie 要从一个牧场到另一个牧场,要求至少要有2条独立的路可以走.现已有m条路,求至少要新 ...
- Python虚拟环境的安装和配置-virtualenv与windows下多个python版本共存
Python虚拟环境的安装和配置-virtualenv与windows下多个python版本共存 windows下多个python版本共存 https://www.python.org/downloa ...
- shell delete with line number
If you want to delete lines 5 through 10 and 12: sed -e '5,10d;12d' file This will print the results ...
- 最详细的Vuex教程
什么是Vuex? vuex是一个专门为vue.js设计的集中式状态管理架构.状态?我把它理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态.简单的说就是data中需要共用的属性. ...