一、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的更多相关文章

  1. netty写Echo Server & Client完整步骤教程(图文)

    1.创建Maven工程 1.1 父节点的pom.xml代码(root pom文件) 1 <?xml version="1.0" encoding="UTF-8&qu ...

  2. Netty Client重连实现

    from:http://itindex.net/detail/54161-netty-client 当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连 ...

  3. Netty Client 重连实现

    当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连.Netty Client有两种情况下需要重连: Netty Client启动的时候需要重连 在程序 ...

  4. netty初探(1)

    参考目录: 1. user-guide : http://netty.io/wiki/user-guide-for-4.x.html 2. demo: http://netty.io/wiki/ 3. ...

  5. Netty 学习 一、初识Netty【原创】

    在过去几年的工作和学习中,比较关注高层次的应用开发,对底层探究较少.实现Web应用的开发,主要依赖Tomcat.Apache等应用服务器,程序员无需了解底层协议,但同样限制了应用的性能和效率.现在开始 ...

  6. 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 ...

  7. User guide for Netty 4.x

    Table of Contents Preface The Solution Getting Started Before Getting Started Writing a Discard Serv ...

  8. netty参考

    前言 问题 现如今我们使用通用的应用程序或者类库来实现系统之间地互相访问,比如我们经常使用一个HTTP客户端来从web服务器上获取信息,或者通过web service来执行一个远程的调用. 然而,有时 ...

  9. Netty4.0学习笔记系列之一:Server与Client的通讯

    http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...

随机推荐

  1. ubuntu安装 LNMP+redis

    一.更新软件源 1.修改软件源为163的源 sudo vim /etc/apt/sources.list 替换源为163的源: deb http://mirrors.163.com/ubuntu/ i ...

  2. MyBatis映射文件中用#和$传递参数的特点

    在MyBatis映射文件中用#和$传递参数的特点, #是以占位符的形式来传递对应变量的参数值的,框架会对传入的参数做预编译的动作, 用$时会将传入的变量的参数值原样的传递过去,并且用$传递传递参数的时 ...

  3. Java之动态代理简介

    图截于<大话设计模式> Proxy模式是常用的设计模式,其特征是代理类与委托类有同样的接口,代理类主要负责为委托类预处理消息.过滤消息.把消息转发给委托类,以及事后处理消息等. 用户可以更 ...

  4. 取分组TOPN好理解案例

  5. MySQL当月负毛利订单明细_20161027

    #当月每天负毛利订单明细 SELECT c.ID,a.city AS 城市,a.username AS 用户ID,a.订单日期,a.订单号,a.销售确认额,a.成本额,a.毛利1, CASE THEN ...

  6. 「51Nod1639」绑鞋带(概率

    1639 绑鞋带  基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题  收藏  关注 有n根鞋带混在一起,现在重复n次以下操作:随机抽出两个鞋带头,把它们绑在一起.可 ...

  7. NFS安装

    安装应用 yum install -y nfs-utils rpcbind   服务器端: 1.启动服务 service nfs start service rpcbind start   2. 编辑 ...

  8. 向nexus远程仓库里面添加JAR

    向nexus远程仓库里面添加JAR 远程仓库:http://10.1.252.21:8081/nexus/index.html admin/admin123 方法一:手动 在左侧选择:Reposito ...

  9. C# 序列化反序列化XML的帮助类

    以下是一个包装的用于序列化反序列化XML和C# 对象的类.  public class XmlSerializeHelper<T>     {         #region Serial ...

  10. TCP 协议的消息

    TCP: SYN ACK FIN RST PSH URG 详解 TCP的三次握手是怎么进行的了:发送端发送一个SYN=1,ACK=0标志的数据包给接收端,请求进行连接,这是第一次握手:接收端收到请求并 ...