android netty导入_Android Netty框架的使用
public abstract class BaseClientMgr extends Subject implementsIClientConnect {protected boolean isRunning; //當前是否正在連接
protected boolean isSending; //是否正在發送 線程是否被占用
private int mPort; //連接服務器的端口號
private int mCommunication; //通訊類型
private int heartTimeOutCount = 0; //記錄心跳超時次數
protected int function = 1200; //關閉連接功能號
public static final int RESPONSE_SUCCESS = 0x401;public static final int RESPONSE_FAIL = 0x402;public static final int RESPONSE_TIMEOUT = 0x403;public static final int REQUEST_HEARTBEAT_TIMEOUT = 0x410; //心跳超時
public static final int NOT_LOGIN = 0x411; //用戶未登錄
private String mConnectKey = "BasicServicesMgr";private String mHost; //連接服務器的IP地址
protected ArrayList mEntityMsg = null; //待發送消息集合
protected Context mContext; //Context對象
protected CommunicationThreadManager mManager; //該通訊層管理器
protected ParseByteThread mParseByteThread = null; //數據解析線程
protected ExecutorService executor; //線程連接池
protected BaseClientMgr(String host, intport, String key) {
init(host, port, key);
}//初始化
private void init(String host, intport, String key) {this.mContext =MeiApp.mContext;
isRunning= false;
isSending= false;
mHost=host;
mPort=port;
mConnectKey=key;
mEntityMsg= new ArrayList();
executor= Executors.newFixedThreadPool(10);
mParseByteThread= new ParseByteThread(this);
executor.execute(mParseByteThread);
}protected Handler basicHandler = newHandler() {
@Overridepublic voidhandleMessage(Message msg) {super.handleMessage(msg);switch(msg.what) {caseClientConstants.REQUEST://發送請求 連接占用
if (mEntityMsg != null && mEntityMsg.size() > 0) {
isSending= true;//清除handler的消息
basicHandler.removeMessages(ClientConstants.REQUEST);
basicHandler.removeMessages(ClientConstants.REQUEST_CREATE_CONNECT);
basicHandler.removeMessages(ClientConstants.REQUEST_SEND_MESSAGE);//請求類型 當為網絡請求時判斷網絡狀態 建立連接//檢查連接是否可用
if(isRunning) {//直接發送消息
basicHandler.removeMessages(ClientConstants.REQUEST_SEND_MESSAGE);
basicHandler.sendEmptyMessage(ClientConstants.REQUEST_SEND_MESSAGE);
}else{//建立連接
basicHandler.removeMessages(ClientConstants.REQUEST_CREATE_CONNECT);
Message msgCreate=Message.obtain();
msgCreate.what=ClientConstants.REQUEST_CREATE_CONNECT;
msgCreate.arg1= 0;
basicHandler.sendMessage(msgCreate);
}
}break;caseClientConstants.REQUEST_CREATE_CONNECT://建立連接
Log.i("mbk", "建立連接!");
isConnect("netty");break;caseClientConstants.REQUEST_SEND_MESSAGE://發送消息
Log.i("mbk", "發送消息!");if(isRunning) {if (mEntityMsg.size() > 0) {
Log.i("mbk", "發送數據!");
sendData(mEntityMsg.get(0));
basicHandler.removeMessages(ClientConstants.REQUEST_TIMEOUT);//設置請求超時
basicHandler.sendEmptyMessageDelayed(ClientConstants.REQUEST_TIMEOUT, 3000);
}else{
Log.i("mbk", "數據發送完成!");
isSending= false;
}
}else{//重新建立連接
basicHandler.removeMessages(ClientConstants.REQUEST_CREATE_CONNECT);
basicHandler.sendEmptyMessage(ClientConstants.REQUEST_CREATE_CONNECT);
}break;caseClientConstants.REQUEST_SEND_HEARTBEAT:
Log.i("mbk", "發送心跳!");
mManager.sendHeart(function);
heartTimeOutCount++;
Log.i("lzy02", "heartTimeOutCount---------------" +heartTimeOutCount);if (heartTimeOutCount >= 3) {//大于等于3則認為與云棒無連接
callBack(null, null, "心跳超時!", REQUEST_HEARTBEAT_TIMEOUT);
}// //發送心跳
basicHandler.removeMessages(ClientConstants.REQUEST_SEND_HEARTBEAT);
basicHandler.sendEmptyMessageDelayed(ClientConstants.REQUEST_SEND_HEARTBEAT,3000);break;case ClientConstants.REQUEST_TIMEOUT://請求超時
Log.i("mbk", "請求超時!");
isRunning= false;
callBack(null, null, "請求超時!", RESPONSE_TIMEOUT);break;
}
}
};public void sendHeartbeat(intfunction) {this.function =function;
}public voidsendData(IEntity entity) {
sendByte(ClientSocketUtils.sendDatas(mEntityMsg.get(0)));
}//建立連接
@Overridepublic voidisConnect(String netType) {
UdpEntity udpEntity= null;int type =CommunicationThreadManager.MBK_COMMUNICATION_NETTY;if (netType.equals("netty")) {//建立一個netty連接
type =CommunicationThreadManager.MBK_COMMUNICATION_NETTY;
mManager= new CommunicationThreadManager(mContext, null, mConnectKey, "192.168.31.241", mPort, type, mCommunicationCallBack);
Log.i("mbk", "發送地址---" + "192.168.31.241");
Log.i("mbk", "發送端口號---" +mPort);/** if (udpEntity != null) { Log.i("lzy02",
* "udpEntity---209----------udpEntity=="+udpEntity.getYunbangIp());
* mManager = new CommunicationThreadManager(mContext, null, mConnectKey,
* "192.168.31.241", mPort, type, mCommunicationCallBack);
* //Toast.makeText(mContext, "已通過Netty發送 ", Toast.LENGTH_SHORT).show();
* Log.i("mbk","netty發送云棒IP號---" + udpEntity.getYunbangIp()); } else {
* Log.i("lzy02", "udpEntity---211----------udpEntity == null");
* callBack(null, null, "無法連接netty!", RESPONSE_FAIL); }*/
//使用netty是時候 清理p2p
P2pClearUp();
}else{
}
Log.i("mbk", "初始化 連接服務器!" +netType);
}
@Overridepublic void sendByte(byte[] b) {try{if (mManager != null) {
mManager.sendDataToServer(newSendData(b));
}else{
isClose();
}
}catch(InterruptedException e) {
isClose();
}
}//服務端回調
private CommunicationCallBack mCommunicationCallBack = newCommunicationCallBack() {
@Overridepublic voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
Log.i("mbk", "--------------------------請求異常--------------------------" +mCommunication);
isRunning= false;
callBack(null, null, "請求異常!", RESPONSE_FAIL);
}
@Overridepublic voidconnected(ChannelHandlerContext ctx) {
Log.i("mbk", "--------------------------連接成功--------------------------" +mCommunication);//mChx = ctx;
isRunning = true;
sendAgain();
}
@Overridepublic voidconnectFailure(Exception e) {
Log.i("mbk", "--------------------------連接服務器失敗--------------------------" +mCommunication);
isRunning= false;
callBack(null, null, "連接服務器失敗!", RESPONSE_FAIL);
}
@Overridepublic void channelRead(ChannelHandlerContext ctx, byte[] msg) {
Log.i("mbk", "--------------------------服務端返回--------------------------" +mCommunication);if (mParseByteThread != null) {
mParseByteThread.sendParseByte(msg);
}
}
@Overridepublic voidcommunicationOutTime() {
Log.i("mbk", "--------------------------連接超時--------------------------" +mCommunication);
isRunning= false;
callBack(null, null, "連接超時!", RESPONSE_TIMEOUT);
}
@Overridepublic voidquestTimeOut() {
Log.i("mbk", "--------------------------請求超時--------------------------" +mCommunication);
isRunning= false;
callBack(null, null, "請求超時!", RESPONSE_TIMEOUT);
}
};
@Overridepublic voidsendAgain() {//連接成功 發起請求
Log.i("mbk", "連接成功,數據重新發送!");//basicHandler.sendEmptyMessage(ClientConstants.REQUEST_SEND_MESSAGE);
basicHandler.sendEmptyMessageDelayed(ClientConstants.REQUEST_SEND_MESSAGE, 500);
}//接收需要發送的實體
@Overridepublic voidsendEntity(IEntity entity) {if (mEntityMsg != null && entity != null) {
mEntityMsg.add(entity);if (!isSending) {//啟動一個發送
Log.i("mbk", "發起請求!REQUEST_NET");
basicHandler.sendEmptyMessage(ClientConstants.REQUEST);
}
}//if (mEntityMsg != null && mEntityMsg.size() == 2) {//mEntityMsg.remove(1);//}
}
@Overridepublic void callBack(PackageHeader header, byte[] data, String desc, inttype) {
basicHandler.removeMessages(ClientConstants.REQUEST_SEND_HEARTBEAT);switch(type) {caseRESPONSE_SUCCESS:
heartTimeOutCount= 0;
basicHandler.sendEmptyMessageDelayed(ClientConstants.REQUEST_SEND_HEARTBEAT,20000);switch(header.getFunction()) {case 9998:
Log.i("mbk", "服務端關閉!");
isClose();break;case 9999:
Log.i("mbk", "成功返回一個心跳!");break;case 999:
Log.i("mbk", "未知錯誤!");
callBack(null, null, "未知錯誤", RESPONSE_FAIL);break;default:
responseSuccess(header, data, desc, type);break;
}break;case REQUEST_HEARTBEAT_TIMEOUT://心跳超時3次認為與云棒無連接
/** Intent m2Intent = new Intent(MeiConfigs.NETWORK_PROMPT);
* m2Intent.putExtra("islogin", "3003");
* MeiApp.mContext.sendBroadcast(m2Intent);*/
break;caseRESPONSE_FAIL:
responseFail(header, data, desc, type);break;caseRESPONSE_TIMEOUT:
responseFail(header, data, desc, type);break;
}
}//請求成功
public void responseSuccess(PackageHeader header, byte[] data, String desc, inttype) {try{if (mEntityMsg.size() > 0 && mEntityMsg.get(0).getHandler() != null) {
IEntity entity= mEntityMsg.get(0);if (data != null && data.length > 0) {
entity.onDecode(new String(data, "utf-8"));//Log.i("mbk","云棒返回---" + "---" + new String(data, "utf-8"));//請求成功
Log.i("lzy02", "1--------------" +entity.getCode());
Log.i("mbk", "返回一條數據!");
Message msg=Message.obtain();
msg.obj=entity;
msg.arg1=header.getFunction();
msg.what=type;
entity.getHandler().sendMessage(msg);
}
}
}catch(Exception e) {
e.printStackTrace();
isClose();
}if (mEntityMsg != null && mEntityMsg.size() > 0) {
mEntityMsg.remove(0);
}
basicHandler.removeMessages(ClientConstants.REQUEST_TIMEOUT);
isSending= false;if (mEntityMsg.size() > 0) {
basicHandler.sendEmptyMessage(ClientConstants.REQUEST);
}
}//請求失敗
public void responseFail(PackageHeader header, byte[] data, String desc, inttype) {
Log.i("mbk", "請求失敗! " +desc);
Message msg=Message.obtain();
msg.obj=desc;
msg.arg1= 0;
msg.what=type;if (mEntityMsg.size() > 0 && mEntityMsg.get(0).getHandler() != null) {
mEntityMsg.get(0).getHandler().sendMessage(msg);
}
isClose();
}//請求本地緩存返回
@Overridepublic voidcallBack(IEntity entity, String desc) {
Log.i("mbk", "回一返個緩存數據! ");if ("cache".equals(desc)) {if (entity != null && entity.getHandler() != null) {
Message msg=Message.obtain();
msg.obj=entity;
msg.what=RESPONSE_SUCCESS;
entity.getHandler().sendMessage(msg);
}
}
}public voidP2pClearUp() {if (mManager != null) {
mManager.p2pCleanup();
}
}
@Overridepublic voidisClose() {
Log.i("mbk", "關閉連接!" +isRunning);if (mManager != null) {if(isRunning) {try{
mManager.sendDataToServer(newSendData(ClientSocketUtils.sendExit(function)));
}catch(InterruptedException e) {
}
}else{
mManager.closeTheadManager();
mManager= null;
}
}if (mParseByteThread != null)
mParseByteThread.closeThread();if (mEntityMsg != null) {
mEntityMsg.clear();
}
P2pClearUp();
basicHandler.removeMessages(ClientConstants.REQUEST_SEND_HEARTBEAT);
basicHandler.removeMessages(ClientConstants.REQUEST_TIMEOUT);
isRunning= false;
isSending= false;
}
@Overridepublic void sendMsgFail(String netType, byte[] msg) {
}
@Overridepublic voidconnectFail(String netType) {
}
@Overridepublic voidisClearMsg() {if (mEntityMsg != null) {
mEntityMsg.clear();
}
}
}
總結
以上是生活随笔為你收集整理的android netty导入_Android Netty框架的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 配置trac界面显示为中文,
- 下一篇: java 安卓调试_【转】Android