Netty 框架基本流程
服务端
package com.mypractice.netty.server; import java.net.InetSocketAddress; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; public class EchoServer {
private final int port; public EchoServer(int port) {
this.port = port;
} public static void main(String[] args) throws Exception { int port = Integer.parseInt("8888");
new EchoServer(port).start();
} public void start() throws Exception {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(boss,worker)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new CostomServerChannelInitializer())
//设置高低水位
.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1)
.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 4); //绑定监听
ChannelFuture f = b.bind().sync();
System.out.println("正在监听...");
f.channel().closeFuture().sync();
} finally {
//关闭EventLoopGroup,释放资源
boss.shutdownGracefully().sync();
worker.shutdownGracefully().sync();
}
}
}
package com.mypractice.netty.server; import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel; public class CostomServerChannelInitializer extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel ch) throws Exception {
// EchoServerHandler被标注为@Shareable,所以我们可以总是使用同样的实例
ch.pipeline().addLast(new EchoServerHandler());
} }
package com.mypractice.netty.server; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.util.CharsetUtil; public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Server 受到client连接:"+ctx.toString());
System.out.println(ctx.channel().config().getWriteBufferHighWaterMark());
System.out.println(ctx.channel().config().getWriteBufferLowWaterMark());
int size = ctx.channel().unsafe().outboundBuffer().size();
System.out.println("size1:" + size);
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
in.writeBytes("hello iam client".getBytes());
System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
ctx.write(in);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);//将未决消息冲刷到远程节点,并且关闭该Channel
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
System.out.println("channge:" +ctx.channel().isWritable());
int size = ctx.channel().unsafe().outboundBuffer().size();
System.out.println("size:" + size);
super.channelWritabilityChanged(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
客户端
package com.mypractice.netty.client; import java.net.InetSocketAddress; 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; 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 worker = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(worker)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new CostomChannelInitializer()); ChannelFuture f = b.connect().sync(); // 连接到远程节点,阻塞等待直到连接完成
f.channel().closeFuture().sync(); // 阻塞,直到Channel关闭
System.out.println("client close");
} finally {
worker.shutdownGracefully().sync(); // 关闭线程池并且释放所有的资源
}
} public static void main(String[] args) throws Exception {
// if (args.length != 2) {
// System.err.println(
// "Usage: " + EchoClient.class.getSimpleName() +
// " <host> <port>");
// return;
// } String host = "127.0.0.1";// args[0];
int port = 8888;// Integer.parseInt(args[1]);
new EchoClient(host, port).start();
}
}
package com.mypractice.netty.client; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel; public class CostomChannelInitializer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel sc) throws Exception {
ChannelPipeline pipeline = sc.pipeline();
pipeline.addLast(new EchoClientHandler());
} }
package com.mypractice.netty.client; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil; //@Sharable //⇽--- 标记该类的实例可以被多个Channel共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
/**
* 收到链接时出发
*/
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("rock!");
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", // ⇽--- 当被通知Channel是活跃的时候,发送一条消息
CharsetUtil.UTF_8));
}
/**
* 收到数据时触发
*/
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
ByteBuf in = (ByteBuf) msg;
System.out.println("Client ##received: " + in.toString(CharsetUtil.UTF_8));
super.channelRead(ctx, msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, // ⇽--- 在发生异常时,记录错误并关闭Channel
Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
Netty 框架基本流程的更多相关文章
- Netty:数据处理流程
Netty作为异步的.事件驱动一个网络通信框架,使用它可以帮助我们快速开发高性能高可靠性的网络服务. 为了更好的使用Netty来解决开发中的问题,学习Netty是很有必要的. Netty现在主流有三个 ...
- NetCore Netty 框架 BT.Netty.RPC 系列随讲 二 WHO AM I 之 NETTY/NETTY 与 网络通讯 IO 模型之关系?
一:NETTY 是什么? Netty 是什么? 这个问题其实百度上一搜一堆. 这是官方话的描述:Netty 是一个基于NIO的客户.服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个 ...
- Netty关闭连接流程分析
在实际场景中,使用Netty4来实现RPC框架,服务端一般会验证协议,最简单的方法的协议探测,判断魔数是否正确.如果服务端无法识别协议会立即抛出异常,并主动关闭连接,此时客户端会收到read信号,在发 ...
- struts2 框架处理流程
struts2 框架处理流程 流程图如下: 注意:StrutsPrepareAndExecuteFilter替代了2.1.3以前的FilterDispatcher过滤器,使得在执行Action之前可以 ...
- SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>
此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...
- Android Netty框架的使用
Netty框架的使用 1 TCP开发范例 发送地址---192.168.31.241 发送端口号---9223 发送数据 { "userid":"mm910@mbk.co ...
- OpenCart框架运行流程介绍
框架运行流程介绍 这样的一个get请求http://hostname/index.php?route=common/home 发生了什么? 1. 开始执行入口文件index.php. 2. requi ...
- 基于netty框架的Socket传输
一.Netty框架介绍 什么是netty?先看下百度百科的解释: Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开 ...
- J2EE进阶(六)SSH框架工作流程项目整合实例讲解
J2EE进阶(六)SSH框架工作流程项目整合实例讲解 请求流程 经过实际项目的进行,结合三大框架各自的运行机理可分析得出SSH整合框架的大致工作流程. 首先查看一下客户端的请求信息: 对于一个Web项 ...
随机推荐
- IOS中iframe的滚动条不启作用
引自:https://www.cnblogs.com/weinan/archive/2013/01/05/2832800.html 问题描述: iframe设置了高度(例如500px).倘若ifram ...
- 《人件》读后感 PB16110698 第十周(~5.15)
在同组马同学的推荐下,我阅读了<人件>一书.在我看来,本书与之前读过的几本软工书籍相比,最大的特色就是地地道道的“以人为本”:不同于<人月神话><构建之法>等结合软 ...
- JS对象 四舍五入round() round() 方法可把一个数字四舍五入为最接近的整数。 语法: Math.round(x)
四舍五入round() round() 方法可把一个数字四舍五入为最接近的整数. 语法: Math.round(x) 参数说明: 注意: 1. 返回与 x 最接近的整数. 2. 对于 0.5,该方法将 ...
- sql语句之条件,分页,排序
sql语句之条件,分页,排序
- 阿里云在云栖大会发布RPA最新3.4版本,将与达摩院联合探索人工智能领域
9月26日,在2019年杭州云栖大会上,阿里云发布了RPA最新V3.4版本,全新升级了增加诸如录屏审计.JAVA应用录制能力.达摩院OCR内置组件.语法检查与智能提示能力增强等功能. RPA全名称Ro ...
- eclipse配置外部工具利用javah编译生成头文件
1. 点击eclipse工具栏外部工具按钮,打开配置外部工具 2. 新建一个启动配置,起名为Generate C and C++ Header File,按照下图配置好相应的参数 3. 运行该工具时, ...
- 类的反射实例(servlet的抽取)
类的反射实例 具体以后我们写的时候不用写BaseServlet,因为各种框架都已经给我们写好了 所以,user对应的servlet的界面长这样:
- Linq Lambda 中group by多列后count数量的写法
直接上代码: List<Student> ss = new List<Student>(); Student ss1 = , Age = , Name = " }; ...
- 资源-Android:Android
ylbtech-资源-Android:Android 1.返回顶部 1. https://developer.android.google.cn/studio 2. 2.返回顶部 1. 1.1 1.2 ...
- Mybatis笔记 – insert语句中主键的返回
在DBMS中可以使用insert语句显示指定自增主键值,但Mybatis中不可,即使指定了也无效,可以使用特殊的方式返回主键. 一.自增主键返回 mysql自增主键执行insert提交 ...