不多说了,直接贴代码
大家好,如果做即时通讯,相信大家对socket也有一定的了解,下面主要是对socket长连接,数据封包解包,外加protobuf的例子,希望能对各位有所帮助
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.ReentrantLock;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
/**
* socket管理类
* @author ZengJ
*
*/
public class IPPushManager{
public static final String tag = IPPushManager.class.getSimpleName();
private String mHostname;
private int mPort;
private PushListener mPushListener;
public static IPPushManager pushManager;
/**
* 写到服务器的处理器
*/
private ReadThread mReadThread;
private HandlerThread mWriteThread;
private HandlerThread mProtocaolThread;
private WriteHandler mWriteHandler;
public static long readWriteBytesCount = 0;
/**
* Socket通道
*/
private Socket mSocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
private ReentrantLock mSockConnectionReentrantLock = new ReentrantLock();
private Context mContext;
private Set mListener = new CopyOnWriteArraySet();
// 保存每次上传器的对象
private HashMap mMapUploadFile = new HashMap();
// 保存每次下载器的对象
private HashMap mMapDownLoadFile = new HashMap();
private IPPushManager(String hostName, int port) {
mHostname = hostName;
mPort = port;
}
public static void init(String hostName, int port) {
if (pushManager == null) {
pushManager = new IPPushManager(hostName, port);
}
}
public static IPPushManager getInstance() {
if (pushManager == null) {
throw new RuntimeException("before call init()");
}
return pushManager;
}
public void addListener(ISocketClient listener) {
if (listener != null) {
mListener.add(listener);
}
}
public void removeListener(ISocketClient listener) {
if (listener != null) {
mListener.remove(listener);
}
}
/**
* 发送消息
*
* @Title: send
* @Description: TODO
* @return: void
*/
public void send(byte[] request) {
if (mWriteHandler != null) {
mWriteHandler.sendMessage(mWriteHandler.obtainMessage(0, request));
}
}
public void setPushListener(PushListener pushListener) {
mPushListener = pushListener;
}
/**
* 建立连接
*
* @Title: connect
* @Description: TODO
* @return: void
*/
public void connect(final OnConnectListener listener) {
new Thread() {
public void run() {
mSockConnectionReentrantLock.lock();
try {
if (isConnected()) {
return;
}
// dissConnect();
InetSocketAddress addr = new InetSocketAddress(mHostname,
mPort);
mSocket = new Socket();
mSocket.connect(addr, 10 * 1000);
if (mSocket.isConnected()) {
mSocket.setKeepAlive(true); // 长连接
mSocket.setTcpNoDelay(true);// 数据不作缓冲,立即发送
mSocket.setSoLinger(true, 0);// socket关闭时,立即释放资源
mInputStream = mSocket.getInputStream();
mOutputStream = mSocket.getOutputStream();
// 初始化协议处理器
mProtocaolThread = new HandlerThread(
"IPPush ProtocaolController");
mProtocaolThread.start();
mReadThread = new ReadThread();
mReadThread.setName("IPPush ReadHandlerThread");
mReadThread.start();
mWriteThread = new HandlerThread(
"IPPush WriteHandlerThread");
mWriteThread.start();
mWriteHandler = new WriteHandler(
mWriteThread.getLooper());
if (listener != null) {
listener.onConnectSuccess(IPPushManager.this);
}
} else {
// 连接失败
if (listener != null) {
listener.onConnectFail(new SocketException("连接失败"));
}
}
} catch (Exception e) {
// 连接失败
if (listener != null) {
listener.onConnectFail(e);
}
dissConnect();
} finally {
mSockConnectionReentrantLock.unlock();
}
};
}.start();
}
/**
* 通道是否打开
*
* @Title: isOpen
* @Description: TODO
* @return
* @return: boolean
*/
public boolean isConnected() {
try {
return mSocket != null && mSocket.isConnected()
&& !mSocket.isInputShutdown()
&& !mSocket.isOutputShutdown();
} catch (Exception e) {
return false;
}
}
public void onPush() {
if (mPushListener != null) {
mPushListener.onPush();
}
}
/**
* 断开连接
*
* @Title: dissConnect
* @Description: TODO
* @return: void
*/
public void dissConnect() {
try {
if (mInputStream != null) {
mInputStream.close();
mInputStream = null;
}
if (mOutputStream != null) {
mOutputStream.close();
mOutputStream = null;
}
if (mSocket != null) {
mSocket.close();
mSocket = null;
}
if (mWriteHandler != null) {
mWriteHandler.sendEmptyMessage(-1);
mWriteHandler = null;
}
readWriteBytesCount = 0;
} catch (Exception e) {
}
}
private class WriteHandler extends Handler {
public WriteHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
if (msg.what == -1) {
getLooper().quit();
return;
}
if (msg.obj != null && msg.obj instanceof byte[]) {
if (!isConnected()) {
// 服务器已断开连接
return;
}
try {
byte[] buffer = (byte[]) msg.obj;
readWriteBytesCount += buffer.length;
mOutputStream.write(buffer);
mOutputStream.flush();
Log.d("IPPush", "-----------------------------");
} catch (IOException e) {
e.printStackTrace();
dissConnect();
LogHelper.e(tag + "_WriteHandler发生了IOException",
e.getMessage());
}
}
super.handleMessage(msg);
}
}
private class ReadThread extends Thread {
public ReadThread() {
}
private boolean readData(byte[] data) {
int length = data.length;
long firstTime = 0;
int i = 0;
while (true) {
if (firstTime == 0) {
firstTime = System.currentTimeMillis();
} else {
if (System.currentTimeMillis() - firstTime > 3000) {
return false;
}
}
try {
int readLength = 0;
if ((readLength = mInputStream.read(data, i, length - i)) == length
- i) {
// 读取成功,数据在data里
Log.d("data", "" + data.length);
return true;
} else {
i += readLength;
}
} catch (IOException e) {
e.printStackTrace();
LogHelper.e(tag + "_Error", e.getMessage());
return false;
}
}
}
@Override
public void run() {//数据读取这一块就根据具体协议来定
try {
StringBuffer stringBuffer = new StringBuffer();
Log.d("stringBuffer", "" + stringBuffer.length());
String line = null;
final byte[] successHeader = new byte[3];
while (isConnected()) {
byte[] header = new byte[4];
if (readData(header)) {
int length = Util.toInt(header);
byte[] data = new byte[length];
if (readData(data)) {
int i = mListener.size();
for (ISocketClient listener : mListener) {
ProtobufHandler.getInstance(mContext).read(
listener, mContext, data);
}
}
}
/*
* if (mInputStream.read(header) == 3) { int length =
* mInputStream.read(); Log.d("length", "" + length); byte[]
* data = new byte[length]; long firstTime = 0; int i = 0;
* while(true){ if(firstTime == 0){ firstTime =
* System.currentTimeMillis(); } else{
* if(System.currentTimeMillis() - firstTime > 3000){ break;
* } } if ((i = mInputStream.read(data, i, length - i)) ==
* length - i) { // 读取成功,数据在data里 Log.d("data", "" +
* data.length); // for (int i = 0; i < data.length; i++) {
* // Log.d("data"+i, "" + data[i]); // }
*
* for(ISocketClient listener : mListener){
* ProtobufHandler.getInstance(mContext).read(listener,
* mContext, data); } break; } else {
*
* } }
*
* }
*/
/*
* try { Thread.sleep(2000); } catch (InterruptedException
* e) { }
*/
}
// while (isConnected()) {
//
//
// byte[] recvMsg2 = recvMsg(mInputStream);
// Log.d("recvMsg2", "" + recvMsg2.length);
// byte[] readByte = Bytes.readByte(recvMsg2);
// Log.d("readByte", "" + readByte.length);
// ProtobufHandler.getInstance(mContext).read(mListener1,
// mContext, readByte);
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// }
// }
} catch (Exception e) {
e.printStackTrace();
LogHelper.e(tag + "_ReadThread发生了IOException", e.getMessage());
} finally {
// dissConnect();
}
// 服务器已断开连接
}
}
/**
* 接收server的信息
*
* @return
* @throws SmsClientException
* @author fisher
*/
public byte[] recvMsg(InputStream inpustream) {
try {
byte len[] = new byte[1024];
int count = inpustream.read(len);
byte[] temp = new byte[count];
for (int i = 0; i < count; i++) {
temp[i] = len[i];
}
return temp;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 上传文件
*
* @return 返回本次请求的flag标识
* @throws ConnectionException
*/
public long upLoadFile(String url, InputStream is, String filename,
Map map, long flag, UploadFileCallback callback)
throws Exception {
UploadFile upLoadFile = new UploadFile(mContext, is, filename, url,
map, callback, flag);
mMapUploadFile.put(flag, upLoadFile);
new Thread(upLoadFile).start();
return flag;
}
/**
* 下载文件
*
* @param url
* @return -1请求失败
* @throws ConnectionException
*/
public int downLoadFile(Context context, String url, int flag,
DownloadFileCallback callback) throws Exception {
if (CommonFuncation.isEmptyOrNullStr(url)) {
return -1;
}
String filename = url.substring(url.lastIndexOf("/") + 1, url.length());
return downLoadFile(context, url, Config.cacheAudioPath, filename,
flag, callback);
}
/**
* 下载文件
*
* @param url
* @param dir
* @param filename
* @return
* @throws ConnectionException
*/
public int downLoadFile(Context context, String url, String dir,
String filename, int flag, DownloadFileCallback callback)
throws Exception {
mMapDownLoadFile.put(flag, null);
File file = new File(dir, filename);
DownloadFile downLoadFile = new DownloadFile(context, callback, url,
filename, file.getAbsolutePath(), flag, file.exists());
new Thread(downLoadFile).start();
return flag;
}
// 关闭下载
public void closeDownLoadFile(int flag) {
if (mMapDownLoadFile.containsKey(flag)) {
mMapDownLoadFile.get(flag).close();
mMapDownLoadFile.remove(flag);
}
}
public static interface OnConnectListener {
public void onConnectSuccess(IPPushManager manager);
public void onConnectFail(Exception e);
}
public static interface PushListener {
/**
* 有推送内容到达
*
* @Title: onPush
* @Description: TODO
* @return: void
*/
public void onPush();
}
}
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
/**
*
* @author ZengJ
* @data 2014-04-24 10:20:15
* @version 1.0.0
*
*
*/
public class IPPushService extends Service {
public final static String tag = IPPushService.class.getSimpleName();
public final static String ACTION_HEART = "com.changyou.rc_sdk.socket。heart";
public final static String ACTION_SEND = "com.changyou.rc_sdk.socket.send";
public final static String PARAMS_SEND = "data";
public final static String NETWORK = ConnectivityManager.CONNECTIVITY_ACTION;
public final static int REQUEST_CODE_HEART_ALARM = 0x99;
private String mHost = "";
private int mPort = 0;
private static final int NET_CHECK_HEART_TIME = 25 * 1000;
private static final int WAP_CHECK_HEART_TIME = 25 * 1000;
public static boolean isOpen = false;
public static int sHeartCount = 0;
private int mHeartCheckTime = NET_CHECK_HEART_TIME;// 25s检测一次心跳状态
private IPPushServiceBinder mIPPushServiceBinder = new IPPushServiceBinder();
private IPPushManager mIPPushManager;
private IPPushHeartReceiver mIPPushHeartReceiver;
HashMap mMaps;
public void registerListener(Type type, ISocketClient listener) {
}
/**
* 启动IPPush服务
*
* @Title: startIPPushService
* @Description: TODO
* @param context
* @return: void
*
*
*/
public static synchronized void startIPPushService(Context context,
String host, int port) {
if (isOpen) {
return;
}
if (isServiceRunning(context)) {
return;
}
isOpen = true;
if (context == null) {
return;
}
try {
context.startService(new Intent(context, IPPushService.class)
.putExtra("host", host).putExtra("port", port));
} catch (Exception e) {
}
}
/**
* 重启IPPush服务
*
* @Title: startIPPushService
* @Description: TODO
* @param context
* @return: void
*/
public static synchronized void restartIPPushService(Context context,
String host, int port) {
if (isOpen) {
return;
}
if (context == null) {
return;
}
closeIPPushService(context);
startIPPushService(context, host, port);
}
/**
* 关闭IPPush服务
*
* @Title: closeIPPushService
* @Description: TODO
* @param context
* @return: void
*/
public static synchronized void closeIPPushService(Context context) {
if (context == null) {
return;
}
try {
context.stopService(new Intent(context, IPPushService.class));
} catch (Exception e) {
}
}
/**
* 用来判断服务是否运行.
*
* @param context
* @param className
* 判断的服务名字:包名+类名
* @return true 在运行, false 不在运行
*/
public static boolean isServiceRunning(Context context) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List serviceList = activityManager
.getRunningServices(Integer.MAX_VALUE);
if (!(serviceList.size() > 0)) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(
IPPushService.class.getName()) == true) {
isRunning = true;
break;
}
}
return isRunning;
}
@Override
public void onCreate() {
super.onCreate();
mIPPushHeartReceiver = new IPPushHeartReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_HEART);
intentFilter.addAction(ACTION_SEND);
intentFilter.addAction(NETWORK);
registerReceiver(mIPPushHeartReceiver, intentFilter);
}
private class IPPushHeartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_HEART.equals(action)) {
LogHelper.d(tag + "_心跳中", "(" + sHeartCount++ + ")...");
if (mIPPushManager == null || !mIPPushManager.isConnected()) {
// 发起注册并连接的任务
LogHelper.d(tag + "_connect", " 失去连接");
connect();
} else {
// 发出心跳包
RCMessage.Builder builder = Params.sendHeartbeat();
byte[] writeHeart = ProtobufHandler.getInstance(context)
.writeHeart(builder, IPPushService.this);
if (writeHeart != null) {
mIPPushManager.send(writeHeart);
}
// RCMessage.Builder builder = RCMessage.newBuilder();
// HeatBit.Builder heatbit = HeatBit.newBuilder();
// heatbit.setUid(ChangYouManager.getInstance().getUid());
// heatbit.setGameKey(ChangYouManager.getInstance().getUid());
// heatbit.setDistrict(ChangYouManager.getInstance().getUid());
// heatbit.setServerid(ChangYouManager.getInstance().getUid());
// heatbit.setNickname(ChangYouManager.getInstance().getUid());
// builder.setHeatBit(heatbit);
// builder.setUri(Type.HEAT_BIT);
// RCMessage message = builder.build();
// byte[] byteArray = message.toByteArray();
// byte[] setByteLength = Bytes.setByteLength(byteArray);
// mIPPushManager.send(setByteLength);
// CommonFuncation.log("write", byteArray.length);
// CommonFuncation.log("setByteLength",
// setByteLength.length);
LogHelper.d(tag + "_HEART", "发送客户端心跳请求");
// 设置下次心跳时间
setCheckHeartTime(NetworkUtil.getNetworkType(context));
setHeartAlarm();
}
} else if (ACTION_SEND.equals(action)) {
if (mIPPushManager != null && mIPPushManager.isConnected()) {
byte[] data = intent.getByteArrayExtra(PARAMS_SEND);
if (data != null) {
mIPPushManager.send(data);
}
}
} else if (NETWORK.equals(action)) {
Log.d("mark", "网络状态已经改变");
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String name = info.getTypeName();
Log.d("mark", "当前网络名称:" + name);
connect();
} else {
Log.d("mark", "没有可用网络");
connect();
}
}
}
}
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (intent == null) {
stopSelf();
return;
}
// 获取启动参数
mHost = intent.getStringExtra("host");
mPort = intent.getIntExtra("port", -1);
LogHelper.d(tag+"_获取启动参数", "获取启动参数");
LogHelper.d(tag+"_Host:", mHost);
LogHelper.d(tag+"_Port:", mPort);
if (TextUtils.isEmpty(mHost) || mPort <= 0) {
LogHelper.d("获取启动参数失败", "获取启动参数失败");
stopSelf();
return;
} else {
connect();
}
}
private void setHeartAlarm() {
setCheckHeartTime(NetworkUtil.getNetworkType(this));
LogHelper.d(tag+"_设置心跳监听:", mHeartCheckTime);
// 注册一个闹钟 心跳这块ELAPSED_REALTIME 这个休眠后是不会发送心跳了,建议加上cpu休眠唤醒,
//但是比较耗电,代码会在最下面,诸君最好是在服务或者application里面添加
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ACTION_HEART);
// PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, i,
// PendingIntent.FLAG_UPDATE_CURRENT);
// long elapsedRealtime = SystemClock.elapsedRealtime();
// alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
// elapsedRealtime, 25*1000, pendingIntent);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
REQUEST_CODE_HEART_ALARM, i, PendingIntent.FLAG_CANCEL_CURRENT);
// 如果系统中已存在该闹钟,先取消
// alarmManager.cancel(pendingIntent);
// 设置闹钟时间(服务器返回的时间是以秒为单位)
long triggerAtTime = SystemClock.elapsedRealtime() + 25 * 1000;
alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
pendingIntent);
LogHelper.d(tag+"_设置心跳监听1:", mHeartCheckTime);
}
/**
* 连接IPPush服务
*
* @Title: connect
* @Description: TODO
* @return: void
*/
private void connect() {
if (!NetworkUtil.isNetworkConnected(this)) {
LogHelper.d(tag+"_connect", " 网络连接不可用");
return;
}
if (mIPPushManager == null) {
mIPPushManager = IPPushManager.getInstance();
mIPPushManager.setPushListener(new PushListener() {
@Override
public void onPush() {
LogHelper.d(tag+"_onPush", "true");
}
});
}
if (!mIPPushManager.isConnected()) {
LogHelper.d(tag+"_connect", " 开始连接");
mIPPushManager.connect(new OnConnectListener() {
@Override
public void onConnectSuccess(IPPushManager manager) {
LogHelper.d(tag+"_connect", " 连接成功");
// // 发起注册请求
// RCMessage.Builder builder=RCMessage.newBuilder();
// HeatBit.Builder heatbit=HeatBit.newBuilder();
// heatbit.setUid(ChangYouManager.getInstance().getUid());
// heatbit.setGameKey(ChangYouManager.getInstance().getUid());
// heatbit.setDistrict(ChangYouManager.getInstance().getUid());
// heatbit.setServerid(ChangYouManager.getInstance().getUid());
// heatbit.setNickname(ChangYouManager.getInstance().getUid());
// builder.setHeatBit(heatbit);
// builder.setUri(Type.HEAT_BIT);
// byte[] write =
// ProtobufHandler.getInstance().write(IPPushService.this,
// builder);
// byte[] setByteLength = Bytes.setByteLength(write);
// CommonFuncation.log("write", write.length);
// CommonFuncation.log("setByteLength",
// setByteLength.length);
// mIPPushManager.send(setByteLength);
// 发送心跳监听
sendBroadcast(new Intent(ACTION_HEART));
}
@Override
public void onConnectFail(Exception e) {
// 稍后重试
LogHelper.d(tag+"_connect", " 连接失败");
}
});
}
}
@Override
public IBinder onBind(Intent intent) {
return mIPPushServiceBinder;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mIPPushHeartReceiver != null) {
unregisterReceiver(mIPPushHeartReceiver);
}
if (mIPPushManager != null) {
// mIPPushManager.dissConnect();
}
isOpen = false;
}
// public void onEventMainThread(NetworkChangeEvent event) {
// CommonFuncation.log("网络状态发生变化:" + event.type);
// setCheckHeartTime(event.type);
// sendBroadcast(new Intent(ACTION_HEART));
// }
/**
* 判断网络状态
*
* @Title: getAPNType
* @Description: TODO
* @param context
* @return
* @return: int
*/
public void setCheckHeartTime(int networkType) {
if (networkType == 0) {
mHeartCheckTime = NET_CHECK_HEART_TIME;
} else if (networkType == 1) {
mHeartCheckTime = NET_CHECK_HEART_TIME;
} else if (networkType == 2) {
mHeartCheckTime = WAP_CHECK_HEART_TIME;
} else if (networkType == 3) {
mHeartCheckTime = NET_CHECK_HEART_TIME;
} else if (networkType == 4) {
mHeartCheckTime = NET_CHECK_HEART_TIME;
} else {
mHeartCheckTime = WAP_CHECK_HEART_TIME;
}
}
class IPPushServiceBinder extends Binder {
public IPPushService getService() {
return IPPushService.this;
}
}
public static interface IIPPushServiceBindListener {
public void onServiceDisconnected();
public void onServiceConnected(IPPushService service);
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.content.Intent;
/**
*
* @author ZengJ
* @data 2014-04-28 14:20:23
*/
public class ProtobufHandler {
public static final String tag = ProtobufHandler.class.getSimpleName();
private long reqNum;
private HashMap mProtoMap;
private List mListnerList;
private static ProtobufHandler protobufHandler;
private ProtobufHandler(Context context) {
reqNum = 0;
mProtoMap = new HashMap();
mListnerList = new ArrayList();
}
public static ProtobufHandler getInstance(Context context) {
if (protobufHandler == null) {
protobufHandler = new ProtobufHandler(context);
}
return protobufHandler;
}
/**
* 客户端数据请求
*
* @param builder
* @return
*/
public void write(Context context, RCMessage.Builder builder,
IProtobufListener protoHolder) {
builder.setMsgSeqno(++reqNum);
RCMessage message = builder.build();
byte[] byteArray = message.toByteArray();
byte[] setByteLength = Bytes.setByteLength(byteArray);
context.sendBroadcast(new Intent(IPPushService.ACTION_SEND).putExtra(
IPPushService.PARAMS_SEND, setByteLength));
LogHelper.d(tag + "_byteArray", byteArray.length);
LogHelper.d(tag + "_setByteLength", setByteLength.length);
ProtoHolder holder = new ProtoHolder(reqNum, protoHolder);
mProtoMap.put(reqNum, reqNum);
}
/**
* 客户端心跳
*
* @param builder
* @return
*/
public byte[] writeHeart(RCMessage.Builder builder,
IProtobufListener protoHolder) {
builder.setMsgSeqno(++reqNum);
RCMessage message = builder.build();
byte[] byteArray = message.toByteArray();
byte[] setByteLength = Bytes.setByteLength(byteArray);
LogHelper.d(tag + "_byteArray", byteArray.length);
LogHelper.d(tag + "_setByteLength", setByteLength.length);
ProtoHolder holder = new ProtoHolder(reqNum, protoHolder);
mProtoMap.put(reqNum, reqNum);
return setByteLength;
}
/**
* 从服务器读取数据
*
* @param bytes
*/
public void read(ISocketClient iSocketClient, Context context, byte[] bytes) {
try {
if (bytes == null) {
return;
}
RCMessage message = RCMessage.parseFrom(bytes);
FilterUtil.getInstance().filterReceiveSocket(iSocketClient,
context, message);
// if (message.hasMsgSeqno() == false) {
// RCMessage.Type type = message.getUri();
// for (ListenerHolder listenerHolder : mListnerList) {
// if (listenerHolder.mType == type)
// listenerHolder.mProtobufListener.handleProto(message);
// }
// return;
// }
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
public void RegisterRecListener(RCMessage.Type type,
IProtobufListener protoListener) {
mListnerList.add(new ListenerHolder(type, protoListener));
}
public void UnregisterRecListener(IProtobufListener protoListener) {
for (Iterator it = mListnerList.iterator(); it
.hasNext();) {
ListenerHolder listenerHolder = it.next();
if (listenerHolder == protoListener)
it.remove();
}
}
class ListenerHolder {
public RCMessage.Type mType;
public IProtobufListener mProtobufListener;
public ListenerHolder(RCMessage.Type type,
IProtobufListener protobufListener) {
mType = type;
mProtobufListener = protobufListener;
}
}
class ProtoHolder {
public long seq;
public IProtobufListener protoHolder;
public ProtoTimeoutRunnable runnable;
public ProtoHolder(long seq, IProtobufListener proListener) {
this.seq = seq;
this.protoHolder = proListener;
this.runnable = new ProtoTimeoutRunnable(this.seq);
}
}
class ProtoTimeoutRunnable implements Runnable {
public long seq;
public ProtoTimeoutRunnable(long seq) {
this.seq = seq;
}
@Override
public void run() {
// 这里应该是超时
if (mProtoMap.containsKey(seq)) {
// ProtoHolder protoHoler = mProtoMap.remove(this.seq);
// protoHoler.protoHandler.handleProtoTimeout();
}
}
}
}
public void acquireWakeLock(){
if(wakeLock == null){
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_TAG);
wakeLock.acquire();
}
}
public void releaseWakeLock(){
if(wakeLock != null && wakeLock.isHeld()){
wakeLock.release();
wakeLock = null;
}
}