使用netty开发服务端程序,主要包括一个服务端程序类,主要负责监听端口,建立连接;还有一个服务端数据处理类,负责处理服务端接收到的业务数据,并进行响应,
先贴上一段负责处理接收数据的demo类
package com.jd.time.handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.Date;
/**
* Created by caozhifei on 2015/4/11.
*/
public class TimeServerHandler extends ChannelHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext context,Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req,"GBK");
System.out.println("The time server receive order :"+body);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "BAD ORDER";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
context.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext context) throws Exception{
context.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext context,Throwable cause){
context.close();
}
}
TimeServerHandler 是通过继承ChannelHandlerAdapter这个类,但是也可以实现netty提供的一个接口ChannelHandler,但是通过继承我们可以有选择性的通过覆盖父类的方法来实现自己的业务逻辑,不用全部实现接口里边的方法,
它对于网络事件进行读写操作,通常我们只需要关注channelRead和exceptionCaught方法。channelRead方法负责冲通道中读取数据,并进行业务逻辑处理,处理完成之后然后再通过ChannelHandlerContext的write方法异步发送应答信息给客户端;channelReadCommplete中的flush方法,则是将消息发送队列中的消息写入到SocketChannel中发送给对方,当发生异常时,则通过exceptionCaught中的方法释放ChannelHandlerContext相关联的句柄资源等,并且进行日志的详细记录。