一、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. PHP的Calling Scope(::调用非静态方法)

    今天在群里发现有人说,PHP可以用::调用非静态方法,一致没这么试过,发现了鸟哥的blog写了这个问题的具体解释,就搬过来: 这个问题乍看, 确实很容易让人迷惑, 但实际上, 造成这样的误解的根本原因 ...

  2. zabbix告警邮件美化

    为了更好的用户体验,我们需要尽量美化我们的输出内容,尽量做到整齐划一,让人看了会有很舒服的感觉, 这个好像和苹果的产品一样,给人一种美感让人感觉非常享受. 一般我们的zabbix告警邮件就是纯文字,建 ...

  3. manacher(无讲解)

    BZOJ3325: [Scoi2013]密码 https://lydsy.com/JudgeOnline/problem.php?id=3325 分析: 根据前i个字符和一些不等和相等条件就可以确定每 ...

  4. ACM学习历程—Hihocoder 1164 随机斐波那契(数学递推)

    时间限制:5000ms 单点时限:1000ms 内存限制:256MB 描述 大家对斐波那契数列想必都很熟悉: a0 = 1, a1 = 1, ai = ai-1 + ai-2,(i > 1). ...

  5. [HAOI 2011] Problem A

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=2298 [算法] 考虑用总人数 - 最多人说真话 显然 , 对于每个人 , 如果他说的 ...

  6. 洛谷 P1496 火烧赤壁

    题目描述 曹操平定北方以后,公元208年,率领大军南下,进攻刘表.他的人马还没有到荆州,刘表已经病死.他的儿子刘琮听到曹军声势浩大,吓破了胆,先派人求降了. 孙权任命周瑜为都督,拨给他三万水军,叫他同 ...

  7. codevs 1576最长严格上升子序列

    传送门 1576 最长严格上升子序列  时间限制: 1 s  空间限制: 256000 KB  题目等级 : 黄金 Gold   题目描述 Description 给一个数组a1, a2 ... an ...

  8. jupyter-notebook重设项目工作路径

    一. . Anaconda Prompt 命令(方法没生效) 1 选择一个用于存放config文件的文件夹(先创建) 2 在cmd中进入该文件夹的路径 3在cmd中 输入​命令 jupyter not ...

  9. ClientSocket.h ClientSocket.cpp

    ClientSocket.h #pragma once // CClientSocket 命令目标 #include "ClientProDlg.h" #include " ...

  10. Windows下caffe安装详解(仅CPU)

    本文大多转载自 http://blog.csdn.net/guoyk1990/article/details/52909864,加入部分自己实战心得. 1.环境:windows 7\VS2013 2. ...