- 什么是Echo服务:就是一个应答服务(回显服务器),客户端发送什么数据,服务端就响应的对应的数据是一个非常有的用于调试和检测的服务;

- IDEA + Maven + jdk8 netty依赖包
- maven地址:https://mvnrepository.com/artifact/io.netty/netty-all/4.1.32.Final
Echo服务对应的启动类和handler处理器
启动类
public class EchoServer {
private int port;
public EchoServer(int port){
this.port = port;
}
/**
* 启动流程
*/
public void run() throws InterruptedException {
//配置服务端线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try{
//启动类
ServerBootstrap serverBootstrap = new ServerBootstrap();
//引导,channel指定是处理器,childHandler添加handler,用来监听已经连接的客户端的Channel的动作和状态
serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
//管道里添加hander
ch.pipeline().addLast(new EchoServerHandler());
}
});
System.out.println("Echo 服务器启动ing");
//绑定端口,同步等待成功
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
//等待服务端监听端口关闭
channelFuture.channel().closeFuture().sync();
}finally {
//优雅退出,释放线程池
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String [] args) throws InterruptedException {
int port = 8088;
if(args.length > 0){
port = Integer.parseInt(args[0]);
}
new EchoServer(port).run();
}
}
这里创建了两个EventLoopGroup对象bossGroup和workerGroup,bossGroup主要用来处理server socket监听client socket的连接请求,server socket接收了新建连接后,会把connection socket放到workerGroup中进行处理,也就是说workerGroup主要用来处理connection socket的网络IO和相关的业务逻辑。
处理器
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf data = (ByteBuf) msg;
System.out.println("服务端收到数据: "+ data.toString(CharsetUtil.UTF_8));
ctx.writeAndFlush(data);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("EchoServerHandle channelReadComplete");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
ChannelInboundHandlerAdapter,看名字中的 IN,就是进入的意思,一般就是事件(event),比如当有数据到来时,channel被激活时或者不可用时,下面介绍几个最常用的。
-
channelActive
通道激活时触发,当客户端connect成功后,服务端就会接收到这个事件,从而可以把客户端的Channel记录下来,供后面复用 -
channelRead
这个必须用啊,当收到对方发来的数据后,就会触发,参数msg就是发来的信息,可以是基础类型,也可以是序列化的复杂对象。 -
channelReadComplete
channelRead执行后触发 -
exceptionCaught
出错是会触发,做一些错误处理
运行后使用telnet进行测试:

Echo服务-客户端程序编写实战
启动类
public class EchoClient {
private String host;
private int port;
public EchoClient(String host, int port){
this.host = host;
this.port = port;
}
public void start() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
//连接到服务端,connect是异步连接,在调用同步等待sync,等待连接成功
ChannelFuture channelFuture = bootstrap.connect().sync();
//阻塞直到客户端通道关闭
channelFuture.channel().closeFuture().sync();
}finally {
//优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
public static void main(String []args) throws InterruptedException {
new EchoClient("127.0.0.1",8088).start();
}
}
处理器
channel激活的时候channelActive,writeAndFlush写入并发送。,回显的时候使用channelRead0接收,处理完毕的时候channelReadComplete,异常的时候exceptionCaught。
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("Client received: " + msg.toString(CharsetUtil.UTF_8));
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Active");
ctx.writeAndFlush(Unpooled.copiedBuffer("小滴课堂 xdclass.net",CharsetUtil.UTF_8));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("EchoClientHandler channelReadComplete");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
SimpleChannelInboundHandler会负责释放指向保存该消息的ByteBuf的内存引用。而ChannelInboundHandlerAdapter在其时间节点上不会释放消息,而是将消息传递给下一个ChannelHandler处理。
client和server通信过程如下图:

Netty实战之Echo服务演示和整个流程分析
分析整个Echo服务各个组件名称和作用
- EventLoop和EventLoopGroup
netty作为一个异步的事件驱动(event drivern)的网络应用程序框架,采用非阻塞的多路复用的网络io模型。连接建立、连接关闭、socket可读、socket可写这些状态的改变称为一个个“事件(event)”,当然事件也可以是应用程序添加的一个任务。
而处理这些event的线程就是一个无限循环(for or while loop),没有事件发生时,线程一直等待事件的产生。当有事件发生时,则处理所有的事件,处理完后则开始下一个循环,继续等待新的事件的发生。所以这种处理逻辑叫做eventLoop,eventLoop与线程是一一对应的,一个eventLoop对应一个线程,一个线程也只有一个eventLoop。而eventLoopGroup主要包含了一组eventLoop(线程池),当然还有许多线程任务分发等管理功能。
eventLoopGroup/eventLoop是netty的核心部件之一,可以说是netty三大核心部件之一,另外两个是channel和pipeline。
eventLoopGroup/eventLoop定义了netty的线程模型,包括channel对socket的操作、pipeline的业务处理、用户提交的任务在内的所有任务的分发调度和执行都是在eventLoopGroup/eventLoop中进行。
- Bootstrap启动引导类
Bootstrap的职责是组装和集成器,将不同的Netty组件组装在一起。另外,ServerBootstrap能够按照应用场景的需要,为组件设置好对应的参数,最后实现Neety服务器的监听和启动。
在Netty中,有两种引导,一是Bootstrap,用于引导客户端或者无连接服务器;另一种便是ServerBootstrap,用于引导面向连接的服务器。
- Channel 生命周期,状态变化
在Netty框架中,Channel是其中之一的核心概念,是Netty网络通信的主体,由它负责同对端进行网络通信、注册和数据操作等功能。
- ChannelHandler和ChannelPipline
当一个ChannelHandler添加到一个ChannelPipeline或从一个ChannelPipeline中移除时,会调用ChannelHandler生命周期中相应的方法。每个方法都会接收一个ChannelHandlerContext参数。
网友评论