Echo 客户端和服务器之间的交互是非常简单的;在客户端建立一个连接之后,它会向服务器发送一个或多个消息,反过来,服务器又会将每个消息回送给客户端。虽然它本身看起来好像用处不大,但它充分地体现了客户端/服务器系统中典型的请求-响应交互模式。
通过同时实现客户端和服务器,我们将能够更加全面地理解 Netty 的 API,好了无需多言,直接上代码,开启netty之路吧。
服务端代码:
所有的 Netty 服务器都需要以下两部分。
至少一个 ChannelHandler — 该组件实现了服务器对从客户端接收的数据的处理,即它的业务逻辑。
引导 — 这是配置服务器的启动代码。至少,它会将服务器绑定到它要监听连接请求的端口上。
首先我们先创建ChannelHandler 和业务逻辑,它的实现负责接收并响应事件通知。
- channelRead() 对于每个传入的消息都要调用;
- channelReadComplete() 通知ChannelInboundHandler最后一次对channel-Read()的调用是当前批量读取中的最后一条消息;
- exceptionCaught() 在读取操作期间,有异常抛出时会调用。
package cn.lbee.echo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
// 将接收到的消息输出到控制台
System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));
// 回复给客户端一个应答消息
ctx.write(Unpooled.copiedBuffer("地瓜收到! Over.", CharsetUtil.UTF_8));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
// 将未处理的消息推送到远程客户端,并且关闭该channel
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 打印异常
cause.printStackTrace();
// 关闭该channel
ctx.close();
}
}
引导服务器 - EchoServer 类
package cn.lbee.echo;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import java.net.InetSocketAddress;
public class EchoServer {
private int port;
public EchoServer(int port) {
this.port = port;
}
public void start() throws Exception{
final EchoServerHandler echoServerHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup(); //创建Event-LoopGroup
try {
ServerBootstrap bootstrap = new ServerBootstrap(); //创建Server-Bootstrap
bootstrap.group(group)
.channel(NioServerSocketChannel.class) //指定使用NIO传输Channel
.localAddress(new InetSocketAddress(port)) //指定端口设置套接字的地址
.childHandler(new ChannelInitializer<SocketChannel>() { //添加一个Handler到子Channel的ChannelPipeline
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(echoServerHandler);
}
});
ChannelFuture future = bootstrap.bind().sync(); //异步绑定服务器,调用sync()方法阻塞等待,知道绑定完成
future.channel().closeFuture().sync(); //获取channel的closeFuture并且阻塞当前的线程直到他完成
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception{
new EchoServer(8888).start();
}
}
客户端代码
Echo 客户端将会:
(1)连接到服务器;
(2)发送一个或者多个消息;
(3)对于每个消息,等待并接收从服务器发回的相同的消息;
(4)关闭连接。
编写客户端所涉及的两个主要代码部分也是业务逻辑和引导
首先还是写一个ChannelHandler 实现客户端逻辑
- channelActive() 其将在一个连接建立时被调用
- channelRead0() 每当接收数据时,都会调用这个方法。需要注意的是,由服务器发送的消息可能会被分块接收。也就是说,如果服务器发送了 5 字节,那么不能保证这 5 字节会被一次性接收。即使是对于这么少量的数据,channelRead0()方法也可能会被调用两次,第一次使用一个持有 3 字节的 ByteBuf(Netty 的字节容器),第二次使用一个持有 2 字节的 ByteBuf。作为一个面向流的协议,TCP 保证了字节数组将会按照服务器发送它们的顺序被接收。
- exceptionCaught() 如同在 EchoServerHandler。
package cn.lbee.echo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.copiedBuffer("地瓜,地瓜,我是土豆!", CharsetUtil.UTF_8));
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("Client received: " + msg.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
引导客户端 - EchoClient
package cn.lbee.echo;
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;
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 group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class) //指定EventLoopGroup以处理客户端事件,适用于NIO传输的Channel类型
.remoteAddress(new InetSocketAddress(host, port)) //设置服务器的地址
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler()); //创建Channel时,向它的Pipeline中添加上文中的EchoClientHandler实例
}
});
ChannelFuture cf = b.connect().sync(); //连接远程节点,阻塞,直到连接完成
cf.channel().closeFuture().sync(); //阻塞,直到channel关闭
} finally {
group.shutdownGracefully().sync(); //关闭线程池并释放所有资源
}
}
public static void main(String[] args) throws Exception {
new EchoClient("192.168.0.86", 8888).start();
}
}
然后执行Server和Client,结果如下:
Server received: 地瓜,地瓜,我是土豆!
Client received: 地瓜收到! Over.
好了,我们已经构建和运行了自己的第一个Netty客户端和服务器,虽然这只是一个简单的应用程序,但是它可以伸缩到支持数千个并发连接哦!本文借鉴了《Netty In Action》,推荐给大家。