Netty(6)关闭
客户端:
public static void main(String[] args) throws Exception {
final SslContext sslCtx;
if (SSL) {
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(),HOST,PORT));
}
p.addLast(new DiscardClientHandler());
}
});
//make the connection attempt.
ChannelFuture f = b.connect(HOST,PORT).sync();
//wait until the connection is closed.
f.channel().closeFuture().sync();
log.info("connection is closed");
} finally {
group.shutdownGracefully();
}
}
或者
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new TelnetClientInitializer()); Channel ch = b.connect(HOST, PORT).channel();
//read commands from the stdbin.
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for(;;) {
String line = in.readLine();
if (line == null) {
break;
}
//send the received line to the server
lastWriteFuture = ch.writeAndFlush(line +"\r\n");
//if user typed the 'bye' command,wait unitl the server closes the connection.
if ("bye".equals(line.toLowerCase())) {
ch.closeFuture().sync();
break;
}
}
//wait unitl all messages are flushed before closing the channel.
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
} finally {
group.shutdownGracefully();
}
}
或者
@Override
protected void channelRead0(ChannelHandlerContext ctx, BigInteger msg) throws Exception {
receivedMessages ++;
if (receivedMessages == FactorialClient.COUNT-start+1) {
//offer(放入)the answer after closing the connection
ctx.channel().close().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
boolean offered = answer.offer(msg);
log.info("offer the answer result:{}",offered);
}
});
}
}
服务端:
1、继承SimpleChannelInboundHandler或ChannelInboundHandlerAdapter的server端
@Override
protected void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
//Generate and write a response
String response;
boolean close = false;
if (request.isEmpty()) {
response = "Please type something.\r\n";
} else if("bye".equals(request.toLowerCase())) {
response = "Have a good day!\r\n";
close = true;
} else {
response = "Did you say '"+request+"'?\r\n";
}
//不需要write ByteBuf,只需write string,因为传递给StringEncoder
ChannelFuture future = ctx.write(response);
if (close) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
如果是短链接,必须在服务端关闭该channel。此时,才能通知到客户端的chanel.future.close()方法。
2、需要解码器(decoder)的server端
在serverHandler类中的channelRead方法中,无需加入future.addListener(ChannelFutureListener.CLOSE);如下,
@Override
protected void channelRead0(ChannelHandlerContext ctx, BigInteger msg) throws Exception {
//计算阶乘并发送到客户端
lastMultiplier = msg;
factorial = factorial.multiply(msg);
ctx.writeAndFlush(factorial);
}
因为,ByteToMessageDecoder类中,已执行了关闭,如下
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
channelInputClosed(ctx, true);
}
Netty(6)关闭的更多相关文章
- Netty关闭连接流程分析
在实际场景中,使用Netty4来实现RPC框架,服务端一般会验证协议,最简单的方法的协议探测,判断魔数是否正确.如果服务端无法识别协议会立即抛出异常,并主动关闭连接,此时客户端会收到read信号,在发 ...
- 我为 Netty 贡献源码 | 且看 Netty 如何应对 TCP 连接的正常关闭,异常关闭,半关闭场景
欢迎关注公众号:bin的技术小屋,本文图片加载不出来的话可查看公众号原文 本系列Netty源码解析文章基于 4.1.56.Final版本 写在前面..... 本文是笔者肉眼盯 Bug 系列的第三弹,前 ...
- Netty系列之Netty可靠性分析
作者 李林锋 发布于 2014年6月19日 | 29 讨论 分享到:微博微信FacebookTwitter有道云笔记邮件分享 稍后阅读 我的阅读清单 1. 背景 1.1. 宕机的代价 1.1. ...
- [编织消息框架][netty源码分析]4 eventLoop 实现类NioEventLoop职责与实现
NioEventLoop 是jdk nio多路处理实现同修复jdk nio的bug 1.NioEventLoop继承SingleThreadEventLoop 重用单线程处理 2.NioEventLo ...
- Netty高可靠性设计:优化建议
尽管Netty的可靠性已经做得非常出色,但是在生产实践中还是发现了一些待优化点,本小节将进行简单说明.希望后续的版本中可以解决,当然用户也可以根据自己的实际需要决定自行优化. 1 发送队列容量上限控 ...
- Netty:option和childOption参数设置说明
Channel配置参数 (1).通用参数 CONNECT_TIMEOUT_MILLIS : Netty参数,连接超时毫秒数,默认值30000毫秒即30秒. MAX_MESSAGES_PER_REA ...
- Netty Bootstrap(图解)|秒懂
目录 Netty Bootstrap(图解) 源码工程 写在前面 图解几个重要概念 父子 channel EventLoop 线程与线程组 通道与Reactor线程组 Channel 通道的类型 启动 ...
- netty可靠性
Netty的可靠性 首先,我们要从Netty的主要用途来分析它的可靠性,Netty目前的主流用法有三种: 1) 构建RPC调用的基础通信组件,提供跨节点的远程服务调用能力: 2) NIO通信框架,用于 ...
- Netty系列之Netty可靠性分析--转载
原文地址:http://www.infoq.com/cn/articles/netty-reliability 1. 背景 1.1. 宕机的代价 1.1.1. 电信行业 毕马威国际(KPMG Inte ...
- netty服务端的创建
服务端的创建 示例代码 netty源码中有一个netty-example项目,不妨以经典的EchoServer作为楔子. // 步骤1 EventLoopGroup bossGroup = new N ...
随机推荐
- Linux网络编程之select、poll、epoll的比较,以及epoll的水平触发(LT)和边缘触发(ET)
Linux的网络通信先后推出了select.poll.epoll三种模式. select有以下三个问题: (1)每次调用select,都需要把fd集合从用户态拷贝到内核态,这个开销在fd很多时会很大. ...
- 文件操作:os模块与os.path模块
一.os与os.path 原创:http://www.cnblogs.com/lovemo1314/archive/2010/11/08/1871781.html os模块用于处理文件及文件夹,包括文 ...
- Unity 摄像机旋转初探
接触打飞机的游戏时都会碰见把摄像机绕 x 轴顺时针旋转 90°形成俯瞰的视角的去看飞船.也没有多想,就感觉是坐标系绕 x 轴旋转 90°完事了.但是昨天用手比划发一下发现不对.我就想这样的话绕 x 轴 ...
- deep QA 基于生成的chatbot系统
deep QA: https://github.com/Conchylicultor/DeepQA 基于论文:https://arxiv.org/pdf/1506.05869.pdf 基于生成的c ...
- tcp攻击
- NPM 在MacOSX中的使用技巧
经常看到有人说『为啥npm install 的时候报错,显示EACCESS错误…』,之前大家都是sudo大法解决问题,也没太在意. 至于这个问题是brew安装工具的时候造成的,还是系统修改磁盘权限造成 ...
- 洛谷P1080(NOIP2012)国王游戏——贪心排序与高精度
题目:https://www.luogu.org/problemnew/show/P1080 排序方法的确定,只需任取两个人,通过比较与推导,可以得出ai*bi小的人排在前面: 高精度写的时候犯了些细 ...
- I/O:Unit1
编程,从键盘读入学生成绩(0~100分),共15名学生,计算并显示总分.平均成绩.单的学生成绩 ; sum: avg: DATA1 SEGMENT STU DB ,,,,,,,,,,,,,, SUM ...
- POJ2349(求生成树中符合题意的边)
Arctic Network Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 14977 Accepted: 4777 D ...
- 系统启动挂载根文件系统时Kernel panic
转自:http://qiuye.iteye.com/blog/543595 这类问题很常见,先总体介绍一下解决思路. 能出现让人激动的的控制台,那么系统移植已经接近完成:但是不少人在最后一步出现问题. ...