记录 netty 的 hello world 级实例代码
目录
说明
几乎所有的学习netty资料都是以一个 Echo 程序为开始,
所谓Echo程序 :就是应答服务, 客户端传递什么消息 服务端原封不动的返回给客户端。
Echo程序包含 服务端代码 和 客户端代码, Netty的服务端客户端的代码几乎定死的框架结构。
服务端
启动主体程序 serverBootstrap
package org.example.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author admin
*/
public class EchoServer {
static Logger logger = LoggerFactory.getLogger(EchoServer.class);
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();
serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new EchoServerHandler());
}
});
logger.info(">>>>>>>>>>>Echo 服务端启动...");
//绑定端口,同步等待成功
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
//等待服务端监听端口关闭
channelFuture.channel().closeFuture().sync();
logger.info(">>>>>>>>>>>Echo 服务端关闭!");
} finally {
//优雅退出,释放线程池
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8081;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new EchoServer(port).run();
}
}
服务端 Channel 处理器
package org.example.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
/**
* @author admin
*/
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
static Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf data = (ByteBuf) msg;
logger.info(">>>>>>>>>>>EchoServerHandle 收到数据: {}", data.toString(Charset.forName("GBK")));
ctx.writeAndFlush(data);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
logger.info(">>>>>>>>>>>EchoServerHandle 接受完毕!");
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
logger.info(">>>>>>>>>>>EchoServerHandle 关闭!");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error(">>>>>>>>>>>EchoServerHandle 异常 ", cause);
ctx.close();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
logger.info("EchoServerHandle channelRegistered");
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
logger.info("EchoServerHandle channelUnregistered");
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
logger.info("EchoServerHandle channelActive");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
logger.info("EchoServerHandle channelInactive");
}
}
快速测试服务端
window 打开Dos命令行窗口:
输入 telnet localhost 8081
看是否能进入。
然后观察 后台服务端控制台日志信息:
此时 随便输入一个字母 例如:A 连接将中断,服务端控制台打印:
21:21:21.109 [nioEventLoopGroup-3-5] INFO org.example.netty.EchoServerHandler - >>>>>>>>>>>EchoServerHandle 收到数据: A
21:21:21.109 [nioEventLoopGroup-3-5] INFO org.example.netty.EchoServerHandler - >>>>>>>>>>>EchoServerHandle 接受完毕!
21:21:21.110 [nioEventLoopGroup-3-5] INFO org.example.netty.EchoServerHandler - >>>>>>>>>>>EchoServerHandle 关闭!
21:21:21.110 [nioEventLoopGroup-3-5] INFO org.example.netty.EchoServerHandler - EchoServerHandle channelInactive
21:21:21.110 [nioEventLoopGroup-3-5] INFO org.example.netty.EchoServerHandler - EchoServerHandle channelUnregistered
连接之所以立刻关闭,主要是因为,服务端设置了:
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
logger.info(">>>>>>>>>>>EchoServerHandle 接受完毕!");
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
logger.info(">>>>>>>>>>>EchoServerHandle 关闭!");
}
客户端
启动主体程序 bootstrap
package org.example.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
public class EchoClient {
static Logger logger = LoggerFactory.getLogger(EchoClient.class);
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))
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new EchoClientHandler());
}
});
//连接到服务端,connect是异步连接,在调用同步等待sync,等待连接成功
ChannelFuture channelFuture = bootstrap.connect().sync();
logger.info(">>>>>>>>>>>Echo 客户端启动...");
//阻塞直到客户端通道关闭
channelFuture.channel().closeFuture().sync();
logger.info(">>>>>>>>>>>Echo 客户端关闭!");
} finally {
//优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
new EchoClient("127.0.0.1", 8081).start();
}
}
客户端 Channel 处理器
package org.example.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
/**
* @author admin
*/
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
static Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
logger.info(">>>>>>>>>>>EchoClientHandler 接受到数据: {}", msg.toString(Charset.forName("GBK")));
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
logger.info(">>>>>>>>>>>Active");
ctx.writeAndFlush(Unpooled.copiedBuffer(
"hello,这是客户端发出的echo消息", Charset.forName("GBK")));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
logger.info(">>>>>>>>>>>EchoClientHandler channelReadComplete");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error(">>>>>>>>>>>EchoClientHandler 异常 ", cause);
ctx.close();
}
}
快速测试客户端
运行客户端main方法:
客户端控制台打印:
同时服务端控制台打印:
简要说明 EventLoop
1个 EventLoop 类似一个线程,
1个 Channel 就是一个客户端和服务端的连接通道(看成一个TCP长连接)
1个EventLoop 可以服务多个Channel
1个Channel 只对应一个EventLoop
可以创建多个 EventLoop 来优化资源利用,也就是EventLoopGroup
EventLoopGroup 负责分配 EventLoop 到新创建的 Channel,里面包含多个EventLoop。
回顾一下多线程Reactor模型: