在前面的文章中,对netty的使用都是基于byte类型的,但是在实际情况,直接处理byte数据是很少的,一般都是将这些数据转换成自己定义的一些类型。
也就是说在实际情况下decoder与encoder都是用到比较多的handler类型,想要了解他们是怎么实现的,我觉得首先应该知道他们是怎么使用的,那么就用官方说明的UnixTime作为例子来简单的说民一下decoder与encoder是怎么使用的吧。。。
首先先来看看client端的代码吧,由于代码比较少,这里代码就没有弄注释了,反正也比较的简单,一看就能明白是什么意思,另外没有分好几个类来写,直接在一个类中使用内部类来实现了,这样免得麻烦。。好吧,看代码:
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.MessageBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
public class Client {
public void run() throws InterruptedException {
EventLoopGroup worker = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(worker);
b.channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<NioSocketChannel>(){
@Override
protected void initChannel(NioSocketChannel ch)
throws Exception {
// TODO Auto-generated method stub
ch.pipeline().addLast(new TimeDecoder(), new ClientHandler());
}
});
ChannelFuture f = b.connect("127.0.0