使用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相關聯的句柄資源等,並且進行日誌的詳細記錄。