客户端:

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)关闭的更多相关文章

  1. Netty关闭连接流程分析

    在实际场景中,使用Netty4来实现RPC框架,服务端一般会验证协议,最简单的方法的协议探测,判断魔数是否正确.如果服务端无法识别协议会立即抛出异常,并主动关闭连接,此时客户端会收到read信号,在发 ...

  2. 我为 Netty 贡献源码 | 且看 Netty 如何应对 TCP 连接的正常关闭,异常关闭,半关闭场景

    欢迎关注公众号:bin的技术小屋,本文图片加载不出来的话可查看公众号原文 本系列Netty源码解析文章基于 4.1.56.Final版本 写在前面..... 本文是笔者肉眼盯 Bug 系列的第三弹,前 ...

  3. Netty系列之Netty可靠性分析

      作者 李林锋 发布于 2014年6月19日 | 29 讨论 分享到:微博微信FacebookTwitter有道云笔记邮件分享 稍后阅读 我的阅读清单   1. 背景 1.1. 宕机的代价 1.1. ...

  4. [编织消息框架][netty源码分析]4 eventLoop 实现类NioEventLoop职责与实现

    NioEventLoop 是jdk nio多路处理实现同修复jdk nio的bug 1.NioEventLoop继承SingleThreadEventLoop 重用单线程处理 2.NioEventLo ...

  5. Netty高可靠性设计:优化建议

    尽管Netty的可靠性已经做得非常出色,但是在生产实践中还是发现了一些待优化点,本小节将进行简单说明.希望后续的版本中可以解决,当然用户也可以根据自己的实际需要决定自行优化. 1  发送队列容量上限控 ...

  6. Netty:option和childOption参数设置说明

    Channel配置参数 (1).通用参数 CONNECT_TIMEOUT_MILLIS :   Netty参数,连接超时毫秒数,默认值30000毫秒即30秒. MAX_MESSAGES_PER_REA ...

  7. Netty Bootstrap(图解)|秒懂

    目录 Netty Bootstrap(图解) 源码工程 写在前面 图解几个重要概念 父子 channel EventLoop 线程与线程组 通道与Reactor线程组 Channel 通道的类型 启动 ...

  8. netty可靠性

    Netty的可靠性 首先,我们要从Netty的主要用途来分析它的可靠性,Netty目前的主流用法有三种: 1) 构建RPC调用的基础通信组件,提供跨节点的远程服务调用能力: 2) NIO通信框架,用于 ...

  9. Netty系列之Netty可靠性分析--转载

    原文地址:http://www.infoq.com/cn/articles/netty-reliability 1. 背景 1.1. 宕机的代价 1.1.1. 电信行业 毕马威国际(KPMG Inte ...

  10. netty服务端的创建

    服务端的创建 示例代码 netty源码中有一个netty-example项目,不妨以经典的EchoServer作为楔子. // 步骤1 EventLoopGroup bossGroup = new N ...

随机推荐

  1. 【转】PHP生成器 (generator)和协程的实现

    原文地址:https://phphub.org/topics/1430 1.一切从 Iterator 和 Generator 开始 为便于新入门开发者理解,本文一半篇幅是讲述迭代器接口(Iterato ...

  2. densenet tensorflow 中文汉字手写识别

    densenet 中文汉字手写识别,代码如下: import tensorflow as tf import os import random import math import tensorflo ...

  3. listen and translation exercise 53

    It was hard work and there weren't any interesting things for him. You should be an expert with comp ...

  4. hdu-5816 Hearthstone(状压dp+概率期望)

    题目链接: Hearthstone Time Limit: 2000/1000 MS (Java/Others)     Memory Limit: 65536/65536 K (Java/Other ...

  5. appium 特殊操作

      一.触摸操作   1.driver.tap([坐标],持续点击时间) 除了定位到元素的点击外,也可以通过tab实现坐标的点击 driver.tap(driver.tap([(216,1776)], ...

  6. bzoj 4453 cys就是要拿英魂! —— 后缀数组+单调栈+set

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4453 这种问题...一般先把询问离线,排序: 区间对后缀排名的影响在于一些排名大而位置靠后的 ...

  7. C#的Unit Test如何根据exception来判断函数是否执行正确

    添加ExpectedException属性, 然后指定异常类型, catch后决定Assert.IsTrue The following class contains the method to te ...

  8. 功能测试工具Selenium IDE

    Selenium IDE:一个专门用于Firefox浏览器的插件,能够录制回放用户在Firefox中的行为,并把所记录的Selenese (Selenium Commands)转化为HTML/Java ...

  9. 【机器学习】分类算法——Logistic回归

    一.LR分类器(Logistic Regression Classifier) 在分类情形下,经过学习后的LR分类器是一组权值w0,w1, -, wn,当测试样本的数据输入时,这组权值与测试数据按照线 ...

  10. 使用c语言实现的常用函数

    /* 为了面试准备的,有些在工作中也可以用用,本人算法方面比较欠缺,如果有更优秀的算法麻烦告诉我啊 */ /* strcat的实现 */ #include <assert.h> char* ...