k客户端:

package cn.itcast_03_netty.sendorder.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress; import cn.itcast_03_netty.sendobject.coder.PersonEncoder; /**
* • 连接服务器 • 写数据到服务器 • 等待接受服务器返回相同的数据 • 关闭连接
*
* @author wilson
*
*/
public class EchoClient { private final String host;
private final int port; public EchoClient(String host, int port) {
this.host = host;
this.port = port;
} public void start() throws Exception {
EventLoopGroup nioEventLoopGroup = null;
try {
// 客户端引导类
Bootstrap bootstrap = new Bootstrap();
// EventLoopGroup可以理解为是一个线程池,这个线程池用来处理连接、接受数据、发送数据
nioEventLoopGroup = new NioEventLoopGroup();
bootstrap.group(nioEventLoopGroup)//多线程处理
.channel(NioSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel
.remoteAddress(new InetSocketAddress(host, port))//地址
.handler(new ChannelInitializer<SocketChannel>() {//业务处理类
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new EchoClientHandler());//注册handler
}
});
// 链接服务器
ChannelFuture channelFuture = bootstrap.connect().sync();
channelFuture.channel().closeFuture().sync();
} finally {
nioEventLoopGroup.shutdownGracefully().sync();
}
} public static void main(String[] args) throws Exception {
new EchoClient("localhost", 20000).start();
}
} /*
客户端连接服务器,开始发送数据……
client 读取server数据..
服务端数据为 :Sun May 13 10:32:47 CST 2018
*/
package cn.itcast_03_netty.sendorder.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import cn.itcast_03_netty.sendobject.bean.Person; public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
// 客户端连接服务器后被调用
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客户端连接服务器,开始发送数据……");
byte[] req = "QUERY TIME ORDER".getBytes();//消息
ByteBuf firstMessage = Unpooled.buffer(req.length);//发送类
firstMessage.writeBytes(req);//发送
ctx.writeAndFlush(firstMessage);//flush
} // • 从服务器接收到数据后调用
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
throws Exception {
System.out.println("client 读取server数据..");
// 服务端返回消息后
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("服务端数据为 :" + body);
} // • 发生异常时被调用
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println("client exceptionCaught..");
// 释放资源
ctx.close();
}
}

服务端:

package cn.itcast_03_netty.sendorder.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import cn.itcast_03_netty.sendobject.coder.PersonDecoder; /**
* • 配置服务器功能,如线程、端口 • 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么
*
* @author wilson
*
*/
public class EchoServer { private final int port; public EchoServer(int port) {
this.port = port;
} public void start() throws Exception {
EventLoopGroup eventLoopGroup = null;
try {
//server端引导类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//连接池处理数据
eventLoopGroup = new NioEventLoopGroup();
serverBootstrap.group(eventLoopGroup)
.channel(NioServerSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel
.localAddress("localhost",port)//设置InetSocketAddress让服务器监听某个端口已等待客户端连接。
.childHandler(new ChannelInitializer<Channel>() {//设置childHandler执行所有的连接请求
@Override
protected void initChannel(Channel ch) throws Exception {
// 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2
// 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1
ch.pipeline().addLast(new EchoInHandler1());
ch.pipeline().addLast(new EchoInHandler2());
ch.pipeline().addLast(new EchoOutHandler1());
ch.pipeline().addLast(new EchoOutHandler2()); }
});
// 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定,然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。
ChannelFuture channelFuture = serverBootstrap.bind().sync();
System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());
channelFuture.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully().sync();
}
} public static void main(String[] args) throws Exception {
new EchoServer(20000).start();
}
} /*
开始监听,端口为:/127.0.0.1:20000
in1
in2
接收客户端数据:QUERY TIME ORDER
server向client发送数据
Complete1
*/
package cn.itcast_03_netty.sendorder.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.Date; import cn.itcast_03_netty.sendobject.bean.Person; public class EchoInHandler1 extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("in1");
// 通知执行下一个InboundHandler
ctx.fireChannelRead(msg);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("Complete1");
ctx.flush();//刷新后才将数据发出到SocketChannel
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
} }
package cn.itcast_03_netty.sendorder.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; import java.util.Date; import cn.itcast_03_netty.sendobject.bean.Person; public class EchoInHandler2 extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("in2");
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("接收客户端数据:" + body);
//向客户端写数据
System.out.println("server向client发送数据");
String currentTime = new Date(System.currentTimeMillis()).toString();
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp); } @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("Complete2");
ctx.flush();//刷新后才将数据发出到SocketChannel
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
} }
package cn.itcast_03_netty.sendorder.server;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise; public class EchoOutHandler1 extends ChannelOutboundHandlerAdapter {
@Override
// 向client发送消息
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
System.out.println("out1");
/*System.out.println(msg);*/ String currentTime = new Date(System.currentTimeMillis()).toString();
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
ctx.flush();
}
}
package cn.itcast_03_netty.sendorder.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise; public class EchoOutHandler2 extends ChannelOutboundHandlerAdapter { @Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
System.out.println("out2");
// 执行下一个OutboundHandler
/*System.out.println("at first..msg = "+msg);
msg = "hi newed in out2";*/
super.write(ctx, msg, promise);
} }

hadoop26----netty,多个handler的更多相关文章

  1. 关于Netty Pipeline中Handler的执行顺序问题

    原文地址:http://blog.csdn.net/wgyvip/article/details/25637651 最近在学习Netty框架,根据官网的教程学着做了几个小测试,都成功了,后面开始试着写 ...

  2. Netty 中的 handler 和 ChannelPipeline 分析

    上一节我们讲了 Netty 的启动流程,从启动流程入手分析了 Reactor 模型的第一步:channel 如何绑定 Selector.然后讲到了 EventLoop 在启动的时候发挥了什么作用.整个 ...

  3. [netty4][netty-handler]netty之idle handler处理

    初始化时记录idle时间,并启动一个延时任务,延时时间为idle时间,延时任务是io.netty.handler.timeout.IdleStateHandler.AllIdleTimeoutTask ...

  4. Netty核心概念(6)之Handler

    1.前言 本节介绍Netty中第三个重要的概念——Handler,这个在前两节都提到了,尤其是Channel和Handler联系紧密.handler本身的设计非常简单,但是所起到的作用却很大,Nett ...

  5. (三)Netty源码学习笔记之boss线程处理流程

    尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6160194.html  本文我们将先从NioEventLoop开始来学习服务端的 ...

  6. (二)Netty源码学习笔记之服务端启动

    尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6129971.html  本文将不会对netty中每个点分类讲解,而是一个服务端启 ...

  7. Netty笔记--ByteBuf释放

    参考资料:http://www.maljob.com/pages/newsDetail.html?id=394 参考资料:http://www.blogjava.net/liuguly/archive ...

  8. netty基础--基本收发

    使用maven构建一个基本的netty收发应用,作为其他应用的基础.客户端使用packet sender工具. 1  添加netty依赖 1  maven netty依赖 <dependency ...

  9. 用Netty开发中间件:网络编程基础

    用Netty开发中间件:网络编程基础 <Netty权威指南>在网上的评价不是很高,尤其是第一版,第二版能稍好些?入手后快速翻看了大半本,不免还是想对<Netty权威指南(第二版)&g ...

  10. Java11实战:模块化的 Netty RPC 服务项目

    Java11实战:模块化的 Netty RPC 服务项目 作者:枫叶lhz链接:https://www.jianshu.com/p/19b81178d8c1來源:简书简书著作权归作者所有,任何形式的转 ...

随机推荐

  1. Hibernate中:不看数据库,不看XML文件,不看查询语句,怎么样能知道表结构?

    Hibernate中:不看数据库,不看XML文件,不看查询语句,怎么样能知道表结构? 解答:可以看与XML文件对应的域模型.

  2. 关于JSON日期格式显示及My97日期控件

    1.My97日期控件.显示不同的日期格式,可以调整"dateFmt“的参数来配置: 详细DEMO:http://www.my97.net/demo/index.htm <p>日期 ...

  3. 卡友友刷MPOS注册开通流程!

    1.下载友刷APP:打开微信扫描机器背面二维码—点击右上角游览器打开 2. 注册-身份证认证-结算卡绑定:用本人手机号注册完成后,顺着进行身份认证.以及储蓄结算卡绑定.具体看下图: 3.绑定机器:选择 ...

  4. html input accept类型

    在上传文件的时候,需要限制指定的文件类型. <input type="file" accept="image/*" /> accept表示可以上传文 ...

  5. 手动编译svn

    #!/bin/bash yum -y remove subversionmkdir -p /dist/{dist,src}cd /dist/dist/bin/rm -f openssl* subver ...

  6. 一次显式GC导致的High CPU问题处理过程(转)

    项目现场反馈系统出现性能问题,具体表现为:所有的客户端响应极其卡顿. 第一反应推测,难道是DB层面出现阻塞?检查v$session会话状态及等待类型未见异常,应该可以排除DB层面原因导致的可能. 继续 ...

  7. 第十五篇:流迭代器 + 算法灵活控制IO流

    前言 标准算法配合迭代器使用太美妙了,使我们对容器(数据)的处理更加得心应手.那么,能不能对IO流也使用标准算法呢?有人认为不能,他们说因为IO流不是容器,没有迭代器,故无法使用标准算法.他们错了,错 ...

  8. 为什么要使用docker

    1. 为什么要使用Docker Docker容器虚拟化的好处 Docker项目的发起人和Docker Inc.的CTO Solomon Hykes认为,Docker在正确的地点.正确的时间顺应了正确的 ...

  9. 【BZOJ4145】[AMPPZ2014]The Prices 状压DP

    [BZOJ4145][AMPPZ2014]The Prices Description 你要购买m种物品各一件,一共有n家商店,你到第i家商店的路费为d[i],在第i家商店购买第j种物品的费用为c[i ...

  10. Html中编码格式的设置,及引入javascript、css的方法

    1.html页面中设置字符编码的格式: <meta http-equiv="Content-Type" content="text/html; charset=ut ...