Netty(1-2)Discard Client
一、DiscardClientHandler
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j; @Slf4j
public class DiscardClientHandler extends SimpleChannelInboundHandler<Object> {
private ByteBuf content;
private ChannelHandlerContext ctx; @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {//(1)
this.ctx = ctx;
content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeZero(DiscardClient.SIZE);
//content = ctx.alloc().directBuffer(DiscardClient.SIZE).writeBytes("1".getBytes(CharsetUtil.UTF_8));
//发送以上消息
generatTraffic();
} @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
content.release();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {//(2)
//Server is supposed to send nothing,but if it sends somethings,discard it.
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
//*************************自定义方法
private void generatTraffic() {
//flush the outbound buffer to the socket.
//once flushed,generate the same amount of traffic again.
ByteBuf buf = content.retainedDuplicate();
ctx.writeAndFlush(buf).addListener(trafficGenerator);
//Console.log((char)buf.readByte());
log.info("{}",(char)buf.getByte(0));
}
private final ChannelFutureListener trafficGenerator = new ChannelFutureListener() {//(3)
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
generatTraffic();
} else {
future.cause().printStackTrace();
future.channel().close();
}
}
};
}
1、发送消息
2、接收服务器返回的消息。由于服务端没有返回消息,所以此处忽略。
3、发送消息后,根据结果的处理。如果成功,继续发送消息;否则,抛出异常,关闭channel。
二、DiscardClient
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DiscardClient {
static final boolean SSL = System.getProperty("ssl") != null;
static final String HOST = System.getProperty("host","127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port","8080"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256")); 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)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
.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();
}
}
}
运行结果:
服务端:

客户端:

Netty(1-2)Discard Client的更多相关文章
- netty写Echo Server & Client完整步骤教程(图文)
1.创建Maven工程 1.1 父节点的pom.xml代码(root pom文件) 1 <?xml version="1.0" encoding="UTF-8&qu ...
- Netty Client重连实现
from:http://itindex.net/detail/54161-netty-client 当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连 ...
- Netty Client 重连实现
当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连.Netty Client有两种情况下需要重连: Netty Client启动的时候需要重连 在程序 ...
- netty初探(1)
参考目录: 1. user-guide : http://netty.io/wiki/user-guide-for-4.x.html 2. demo: http://netty.io/wiki/ 3. ...
- Netty 学习 一、初识Netty【原创】
在过去几年的工作和学习中,比较关注高层次的应用开发,对底层探究较少.实现Web应用的开发,主要依赖Tomcat.Apache等应用服务器,程序员无需了解底层协议,但同样限制了应用的性能和效率.现在开始 ...
- Netty Tutorial Part 1: Introduction to Netty [z]
Netty Tutorial, Part 1: Introduction to Netty Update: Part 1.5 Has Been Published: Netty Tutorial P ...
- User guide for Netty 4.x
Table of Contents Preface The Solution Getting Started Before Getting Started Writing a Discard Serv ...
- netty参考
前言 问题 现如今我们使用通用的应用程序或者类库来实现系统之间地互相访问,比如我们经常使用一个HTTP客户端来从web服务器上获取信息,或者通过web service来执行一个远程的调用. 然而,有时 ...
- Netty4.0学习笔记系列之一:Server与Client的通讯
http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...
随机推荐
- UVA 111 简单DP 但是有坑
题目传送门:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=18201 其实是一道不算难的DP,但是搞了好久,才发现原来是题目没 ...
- NOIP 2014【斗地主】
这真是道大火题. 因为保证数据随机,所以开始很多人直接用搜索 + 贪心水过去了,后来,为了遏制骗分这种不良风气的传播,各大 OJ 相继推出了斗地主加强版-- 正解: 先爆搜顺子,枚举打或不打,打多少张 ...
- SpringBoot_Exception_01_No plugin found for prefix 'spring-boto' in the current project
一.异常现象 spingbott项目在eclipse中执行maven命令:spring-boot:run, 出现异常: No plugin found for prefix 'spring-boto' ...
- 【译】在ES6中如何优雅的使用Arguments和Parameters
原文地址:how-to-use-arguments-and-parameters-in-ecmascript-6 ES6是最新版本的ECMAScript标准,而且显著的改善了JS里的参数处理.我们现在 ...
- Xcode 中的main.m
在几乎所有的程序开发中程序一般都是从main函数开始运行的,那么IOS程序也不例外,在上图中我们可以看到Xcode为我们生成了一个main.m文件: // // main.m // iOS // // ...
- ACM学习历程—HDU 1272 小希的迷宫(并查集)
Description 上次Gardon的迷宫城堡小希玩了很久(见Problem B),现在她也想设计一个迷宫让Gardon来走.但是她设计迷宫的思路不一样,首先她认为所有的通道都应该是双向连通的,就 ...
- 如何在kindle 3上无法进入 http://www.google.com/reader, 先登陆www.google.com, 然后选择阅读器。
如何在kindle 3上无法进入 http://www.google.com/reader, 先登陆www.google.com, 然后选择阅读器.
- RT-Thread OS的启动流程
1.RT进入main之前, SystemInit函数初始化时钟. 2.main函数位于startup.c文件中.进行两个工作 系统开始前,rt_hw_interrupt_disable关闭所有中断. ...
- SimpliciTI协议地址分配
1.多个ED节点和AP正确连接后,AP都会给ED分配一个相应的地址.当某个ED出现意外,比如电源问题,和AP断开连接,AP并不将该ED节点的地址消除.当该ED恢复正常,重新申请加入网络时,AP会检测该 ...
- spring加载hibernate映射文件的几种方式
1. 在Spring的applicationContext.xml中配置映射文件,通常是在<sessionFactory>这个Bean实例中进行的,若配置的映射文件较少时,可以用sessi ...