客户端:

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. 修改ubuntu14.04命令行启动

    方法1: 原来要想默认不进入xwindows,只需编辑文件”/etc/default/grub”, 把 GRUB_CMDLINE_LINUX_DEFAULT=”quiet splash” 改成GRUB ...

  2. kvm初体验之七:attach usb storage device to a VM

    1. virsh attach-disk vm1 /dev/sdb sdc 将host上的/dev/sdb挂载到vm1的/dev/sdc上 2. virsh detach-disk vm1 sdc 将 ...

  3. 分享知识-快乐自己:Spring中的(三种)异常处理机制

    案例目录结构: Web.xml 配置: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application ...

  4. linux 命令:crontab

    一.crond简介 crond 是linux下用来周期性的执行某种任务或等待处理某些事件的一个守护进程,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务 工具,并且会自动启动c ...

  5. Android Studio的技巧

    1.快速添加add unimplements methods:  右键generate 2.快速添加try-catch:左边就有一个小电灯,然后可以选. 3.格式化OPTION + CMD + L ( ...

  6. window系统的HOST详解

    很多用户都知道在Window系统中有个Hosts文件(没有后缀名),在Windows 98系统下该文件在Windows目录,在Windows 2000/XP系统中位于C\Winnt\System32 ...

  7. CF 504 E —— Misha and LCP on Tree —— 树剖+后缀数组

    题目:http://codeforces.com/contest/504/problem/E 快速查询LCP,可以用后缀数组,但树上的字符串不是一个序列: 所以考虑转化成序列—— dfs 序! 普通的 ...

  8. this在方法赋值过程中无法保持(隐式丢失)

    在看<高级程序设计>(我的红宝书) P.183页时遇到下面一个问题 var name = "77"; var obj = { name: "88", ...

  9. The Tomcat server configuration at \Servers\Tomcat v8.0 Server at localhost-config is missing. Check the server for erro

    解决方案 1.选择Eclipse工具栏中的Windows→Perferences 2.remove已经创建的server 3.选择Add重新添加,选择create anew local server ...

  10. httpmodule VS2012 和 VS2013

    http://stackoverflow.com/questions/963545/httpmodule-not-running-with-visual-studio 如果将 httpmodule 配 ...