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项 ...
随机推荐
- 2019-8-31-dotnet-判断程序当前使用管理员运行降低权使用普通权限运行
title author date CreateTime categories dotnet 判断程序当前使用管理员运行降低权使用普通权限运行 lindexi 2019-08-31 16:55:58 ...
- ARM GNU 常用汇编伪指令介绍
abort .abort: 停止汇编 .align absexpr1, absexpr2: 以某种对齐方式,在未使用的存储区域填充值. 第一个值表示对齐方式,4, 8,16 或 32. 第 二个表 ...
- PHP算法之IP 地址无效化
给你一个有效的 IPv4 地址 address,返回这个 IP 地址的无效化版本. 所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 ".". 示例 ...
- Fence
Fence 有一个长度为n的\([1,n]\)墙,有k位工人,第i位工人有参数\(s_i,p_i,l_i\),意思该位工人可以刷包含\(s_i\)的长度小于等于\(l_i\)的区间,报酬为区间长度乘以 ...
- yum -y install python-devel
yum -y install python-devel的时候报错如图: Could not retrieve mirrorlist http://mirrorlist.centos.org/?rele ...
- luoguP2580 于是他错误的点名开始了 [Trie]
题目背景 XS中学化学竞赛组教练是一个酷爱炉石的人. 他会一边搓炉石一边点名以至于有一天他连续点到了某个同学两次,然后正好被路过的校长发现了然后就是一顿欧拉欧拉欧拉(详情请见已结束比赛CON900). ...
- 「题解」:$Simple$
问题 A: $Simple$ 时间限制: 1 Sec 内存限制: 256 MB 题面 题面谢绝公开. 题解 不算数学的数学题?? 直接枚举会重.$60%$两种算法:1.无脑$vis$数组记录.2.$ ...
- C++利用动态数组实现顺序表(不限数据类型)
通过类模板实现顺序表时,若进行比较和遍历操作,模板元素可以通过STL中的equal_to仿函数实现,或者通过回调函数实现.若进行复制操作,可以采用STL的算法函数,也可以通过操作地址实现.关于回调函数 ...
- python实现全局配置和用户配置文件
一.文件目录格式 二.代码 1.conf.__init__.py import importlib import os from conf import gsettings class Setting ...
- 同一个tomcat 两个项目 互相访问接口方法
package com.qif.xdqdm.util; import com.alibaba.fastjson.JSONObject; import java.io.*; import java.ne ...