netty在4.0版本后开始支持安卓平台
Android support
Given that: - mobile devices are becoming more and more powerful,
- the most known issues with NIO and SSLEngine in ADK were fixed since Ice Cream Sandwich, and
- users obviously want to reuse their codecs and handlers in their mobile applications,
we decided to support Android (4.0 or above) officially.(http://netty.io/wiki/new-and-noteworthy-in-4.1.html)
刚刚接触Android,对Android没有深度的了解,必然很多理解都是错误的,有不对的地方请指正。
整体思路: 构建一个 MainLoop,注册消息handler和processor,消息收发通过AsyncTask异步完成。消息数据使用protobuf2.5封装。使用protobuf工具进一步封装,产生所有消息收发的接口类。MainLoop 注册在主线程。最终效果:
以 退出消息为例:
消息发送:
// Generated by the protocol buffer compiler. DO NOT EDIT!
public class GPdlClient {
class ReqTask extends AsyncTask<ReqMsg, Integer, Integer> {
@Override
protected Integer doInBackground(ReqMsg... arg0) {
ReqMsg req = arg0[0];
PdlClient client = null;
try {
client = clientPool.getResource();
client.send(req.getMsgType(), req.getReq());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientPool.returnResource(client);
} catch (Exception e) {
e.printStackTrace();
}
}
return 1;
}
}
public class ReqMsg {
private int msgType;
private GeneratedMessage req;
public ReqMsg(int type, GeneratedMessage msg) {
msgType = type;
req = msg;
}
public int getMsgType() {
return msgType;
}
public void setMsgType(int msgType) {
this.msgType = msgType;
}
public GeneratedMessage getReq() {
return req;
}
public void setReq(GeneratedMessage req) {
this.req = req;
}
}
private void executeReq(ReqMsg msg) {
ReqTask task = new ReqTask();
task.execute(msg);
}
// client pool
private final PdlClientPool clientPool;
public GPdlClient(final PdlClientPool clientPool) {
this.clientPool = clientPool;
}
public PdlClientPool getClientPool() {
return this.clientPool;
}
public void logout(Logout_C2S_Msg msg) {
ReqMsg req = new ReqMsg(GPdlMsg.PDL_Logout_C2S_Msg, msg);
executeReq(req);
}
……
消息处理:
// PdlProcessor 由protobuf自动生成
public class PdlProcessorImpl extends PdlProcessor {
private final MainLoop mainLoop;
@Override
public void logout(Logout_S2C_Msg msg) {
// TODO Auto-generated method stub
}
……
添加功能只需要添加一组消息协议并实现PdlProcessor接口就行了。
|