我们上次跟完了官网的一个例子,对于netty的server大概有些印象,这次我们写完server和client,并且加上编解码。
Netty example of server and client
server
entity
我们用实体类来封装网络数据。
@Data
public class RequestData {
private int intValue;
private String stringValue;
}
request中的数据,一个int,一个string。
@Data
public class ResponseData {
private int intValue;
}
返回我们就返回一个int。
server encoder and decoder
对于client发来的数据,我们要解码。
public class RequestDecoder extends ReplayingDecoder<RequestData> {
private final Charset charset = Charset.forName("UTF-8");
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
RequestData requestData = new RequestData();
requestData.setIntValue(in.readInt());
int strLen = in.readInt();
requestData.setStringValue(in.readCharSequence(strLen,charset).toString());
out.add(requestData);
}
}
我们把传来的数据读出来并且封装在RequestData
中。
所用的解码格式是utf-8
。
注意我们这里的ReplayingDecoder
是一个ChannelInboundHandlerAdapter
。我们可以从它的父类(ByteToMessageDecoder
)查看它的作用:
/**
*decodes bytes in a stream-like fashion
*from one {@link ByteBuf} to an
* other Message type.
* /
它将ByteBuf
转成另一种消息类型。
关于这个ByteBuf
,能说的也很多。在nio下面有个ByteBuffer
和它很像。只是ByteBuffer
每次读的时候要flip()
,而ByteBuf
有读索引和写索引,它们分开工作。
另一方面,我们需要将发送的数据编码:
public class ResponseDataEncoder extends MessageToByteEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
ResponseData responseData = (ResponseData) msg;
out.writeInt(responseData.getIntValue());
}
}
当我们要写的时候,数据已经有了。
我们可以直接把数据写到Channel
中,但现在我们用一个handler来把逻辑分开来,这就清楚一些。
processing handler
public class SimpleProcessingHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//request processing
RequestData requestData = (RequestData) msg;
ResponseData responseData = new ResponseData();
responseData.setIntValue(requestData.getIntValue() * 2);
ChannelFuture future = ctx.writeAndFlush(responseData);
future.addListener(ChannelFutureListener.CLOSE);
System.out.println(requestData);
}
}
我们将request发来的value取出乘以2然后返回回去。这个就是模拟数据处理的逻辑了。
注意ChannelFuture
:
A ChannelFuture represents an I/O operation which has not yet occurred. It means, any requested operation might not have been performed yet because all operations are asynchronous in Netty
它表示还没有发生的io操作。
因为netty是异步的,所以下面的代码:
Channel ch = ...;
ch.writeAndFlush(message);
ch.close();
可能在数据还没有发出去之前就close了。
如何做到写操作完成之后再close呢?只要我们给返回的future
上加一个ChannelFutureListener
就行了。
netty server
下面构建server:
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDecoder(), new ResponseDataEncoder(),
new SimpleProcessingHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;
new NettyServer(port).run();
}
}
这和之前的例子是一样的。注意,我们在pipeline中加入了
ch.pipeline().addLast(
new RequestDecoder(),
new ResponseDataEncoder(),
new SimpleProcessingHandler());
client
client encoder and decoder
客户端的编解码正好是相反的。对于request它要encode,对于response它要decode。
public class RequestDataEncoder extends MessageToByteEncoder<RequestData> {
private final Charset charset = Charset.forName("UTF-8");
@Override
protected void encode(ChannelHandlerContext ctx, RequestData msg, ByteBuf out) throws Exception {
out.writeInt(msg.getIntValue());
out.writeInt(msg.getStringValue().length());
out.writeCharSequence(msg.getStringValue(), charset);
}
}
public class ResponseDataDecoder extends ReplayingDecoder<ResponseData> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
ResponseData responseData = new ResponseData();
responseData.setIntValue(in.readInt());
out.add(responseData);
}
}
ClientHandler
同时我们用一个ClientHandler来完成数据发送逻辑:
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
RequestData msg = new RequestData();
msg.setIntValue(1);
msg.setStringValue("my first netty message");
ChannelFuture future = ctx.writeAndFlush(msg);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println((ResponseData)msg);
ctx.close();
}
}
我们重写了两个回调函数。
channelActive
是连接一建立就就回掉,而channelRead
是有数据来才会回调。
从这里也可以理解官网所说的netty是一个event-driven
框架。
netty client
client只需要一个workerGroup
来进行连接并发数据就行了,并不需要监听连接。
public class NettyClient {
public static void main(String[] args) {
String host = "localhost";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup).channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler());
}
});
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
workerGroup.shutdownGracefully();
}
}
}