Commit 4df124bc by 许梦竹

add dev-code

parents
File added
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := \
$(LOCAL_PATH)/Common/include
LOCAL_SRC_FILES := \
Common/src/WNObject.cpp \
Common/src/WNCStringList.cpp \
Common/src/IniFileManager.cpp \
Common/src/WNSocketObserverManager.cpp \
Common/src/WNSocketSelectObserver.cpp \
Common/src/WNSocketObserver.cpp \
Common/src/WNCommonSocket.cpp \
Common/src/WNNotificationCenter.cpp \
Common/src/WNByteBufferManager.cpp \
Common/src/WNByteBuffer.cpp \
Common/src/WNReadWriteLocker.cpp \
Common/src/MD5Checksum.cpp \
Common/src/WNCreticalSection.cpp \
Common/src/WNBitIndex.cpp \
Common/src/WNWorkThread.cpp \
BaseSerialPort.cpp \
PcmPlayer.cpp \
WNMemoryPool.cpp \
TTSManager.cpp \
JNIInterface.cpp
LOCAL_SHARED_LIBRARIES := \
libmedia \
libutils \
libcutils
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE:= libgtsdev
LOCAL_SHARED_LIBRARIES += libstlport
include external/stlport/libstlport.mk
include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
#ifndef _BaseSerialPort_H
#define _BaseSerialPort_H
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
#include <pthread.h>
#include "Common/include/WNNotificationCenter.h"
enum SerialPortType
{
SP_Default = -1,
NearReader,
FarReader,
RelayVoltage
};
class BaseSerialPort
{
public:
BaseSerialPort();
~BaseSerialPort();
bool Start(int iPort, int iBaudRate, SerialPortType type);
void Stop();
private:
void StartRecver();
static void * RecverWrapper(void * p);
int FarRecverProcess();
int NearRecverProcess();
int RelayVoltageRecverProcess();
bool OpenPort(int port);
bool SetParams(int nSpeed, int nBits, char nEvent, int nStop);
void SendCardNumber(int number, SerialPortType type);
bool m_bRunning;
SerialPortType m_type;
int m_iFd;
pthread_t m_thread_recver;
};
#endif //#ifndef _BaseSerialPort_H
\ No newline at end of file
#ifndef _DTCOMMON_H_
#define _DTCOMMON_H_
#define MOD_LOG_TAG "libtts.so"
#define _WANIN_LOG_
#ifdef _WANIN_LOG_
#include <android/log.h>
#define LOG(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, MOD_LOG_TAG, fmt, ##args)
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, MOD_LOG_TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR,MOD_LOG_TAG, fmt, ##args)
#else
#define LOG (...)
#define LOGI(...)
#define LOGE(...)
#endif
#endif //_DTCOMMON_H_
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef ACCALLBACK_H
#define ACCALLBACK_H
#include<new>
#include "stdlib.h"
template<class ret_type, class arg_type>
class function_base
{
public:
function_base() {}
virtual ~function_base(){}
virtual ret_type operator() (arg_type) = 0;
};
template<class ret_type, class arg_type>
class function_impl_normal: public function_base<ret_type, arg_type>
{
public:
typedef ret_type (* NORM_PROC) (arg_type);
explicit function_impl_normal(NORM_PROC proc): norm_proc_(proc) {}
ret_type operator() (arg_type arg) { return norm_proc_(arg); }
private:
NORM_PROC norm_proc_;
};
template<class ret_type, class arg_type>
class function
{
public:
typedef ret_type (* NORM_PROC) (arg_type);
explicit function(function_base<ret_type, arg_type>* fun): fun_(fun), ref_(new int(1)) {}
function(NORM_PROC proc = 0): fun_(new function_impl_normal<ret_type, arg_type>(proc)), ref_(new int(1)) {}
ret_type operator() (arg_type arg) { fun_->operator()(arg); }
~function()
{
Release();
}
void Release()
{
*ref_ -= 1;
if (*ref_ == 0)
{
delete ref_;
delete fun_;
}
}
function(const function& fun)
{
fun_ = fun.fun_;
ref_ = fun.ref_;
*ref_ += 1;
}
void operator=(const function& fun)
{
Release();
fun_ = fun.fun_;
ref_ = fun.ref_;
*ref_ += 1;
}
private:
int* ref_;
function_base<ret_type, arg_type>* fun_;
};
template<class CS, class ret_type, class arg_type>
class function_impl: public function_base<ret_type, arg_type>
{
public:
typedef ret_type (CS::* PROC)(arg_type);
function_impl(CS* obj, PROC proc): obj_(obj), proc_(proc) {}
ret_type operator() (arg_type arg) { return (obj_->*proc_)(arg); }
private:
CS* obj_;
PROC proc_;
};
template<class CS, class ret_type, class arg_type>
function<ret_type, arg_type> bind(ret_type (CS::* proc)(arg_type), CS* pc)
{
function_base<ret_type, arg_type>* pf = new function_impl<CS, ret_type, arg_type>(pc, proc);
return function<ret_type, arg_type>(pf);
}
template<class CS, class ret_type>
function<ret_type, void> bind(ret_type (CS::* proc)(), CS* pc)
{
function_base<ret_type, void>* pf = new function_impl<CS, ret_type, void>(pc, proc);
return function<ret_type, void>(pf);
}
struct _ACCallbackOpCodes
{
unsigned char tag; // CALL e8
long* offset; // offset (dest - src - 5, 5=sizeof(tag + offset))
long* _this; // a this pointer
long* _func; // pointer to real member function address
};
static void STDACJMPProc()
{
asm
(
"POP R7\n"
"mov R6 , [R7 + 4]\n" // func
"MOV R7 , [R7]\n" // this
"BL R6\n"
);
}
static long* CalcJmpOffset(long* Src, long* Dest)
{
return (long*)(Dest - (Src + 5));
}
template<typename _TPStdFunc, class _TClass, typename _TPMemberFunc>
class ACCallback
{
public:
_TClass *m_pThis;
_TPMemberFunc m_pFunc;
private:
_TPStdFunc m_pStdFunc;
void MakeCode()
{
if (m_pStdFunc) free(m_pStdFunc);
m_pStdFunc = (_TPStdFunc)malloc(sizeof(_ACCallbackOpCodes));
_ACCallbackOpCodes *p = (_ACCallbackOpCodes *)m_pStdFunc;
p->_func = *(int* *)&m_pFunc;
p->_this = (int*)m_pThis;
p->tag = 0xE8;
p->offset = CalcJmpOffset((int*)p, (int*)STDACJMPProc);
}
public:
ACCallback<_TPStdFunc, _TClass, _TPMemberFunc>()
{
}
ACCallback<_TPStdFunc, _TClass, _TPMemberFunc>(_TClass* pThis,
_TPMemberFunc pFunc
)
{
m_pFunc = pFunc;
m_pThis = pThis;
m_pStdFunc = 0;
// MakeCode();
}
void Assign(_TClass* pThis,
_TPMemberFunc pFunc
)
{
m_pFunc = pFunc;
m_pThis = pThis;
m_pStdFunc = 0;
//MakeCode();
}
~ACCallback<_TPStdFunc, _TClass, _TPMemberFunc>()
{
//::VirtualFree(m_pStdFunc, 0, MEM_RELEASE);
}
operator _TPStdFunc()
{
return m_pStdFunc;
}
};
template <typename _TPStdFunc>
class ACCallbackEx
{
template <typename _TClass, typename _TPMemberFunc>
void MakeCode(_TClass* pThis, _TPMemberFunc pMenberFunc)
{
/*FreeCode();
mpStdFunc = (_TPStdFunc)::VirtualAlloc(0, sizeof(_ACCallbackOpCodes), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
_ACCallbackOpCodes *p = (_ACCallbackOpCodes *)mpStdFunc;
p->_func = *(int* *)&pMenberFunc;
p->_this = (int*)pThis;
p->tag = 0xE8;
p->offset = CalcJmpOffset((int*)p, (int*)STDACJMPProc);*/
}
public:
ACCallbackEx()
{
mpStdFunc = 0;
}
~ACCallbackEx()
{
// FreeCode();
}
operator _TPStdFunc()
{
return mpStdFunc;
}
_TPStdFunc StdFnPtr()
{
return mpStdFunc;
}
template <typename _TClass, typename _TPMemberFunc>
void SetCallBackMemberFunc(_TClass* pThis, _TPMemberFunc pMenberFunc)
{
//MakeCode(pThis, pMenberFunc);
//mpStdFunc = std::bind(pMenberFunc , pThis, _1 );
//bind_base0<void>* tobj0 = bindfun(pThis,pMenberFunc);
f = bind(pMenberFunc,pThis);
}
void operator()(int i=0){
}
void FreeCode()
{
if (mpStdFunc)
{
//::VirtualFree(mpStdFunc, 0, MEM_RELEASE);
mpStdFunc = 0;
}
}
public:
_TPStdFunc mpStdFunc;
function<void ,int> f;
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef INIFILEMANAGER_H
#define INIFILEMANAGER_H
#include "WNCLoopList.h"
//#include "EBaseFunctions.h"
#include <string>
#include <sstream>
#include <ctype.h>
using namespace std;
class IniSectionInfo;
class IniFileManager;
typedef unsigned char u_char;
#ifndef INI_CRLF
#define INI_CRLF "\r\n"
#endif
/*
* This array is designed for mapping upper and lower case letter
* together for a case independent comparison. The mappings are
* based upon ascii character sequences.
*/
int strcasecmp(const char *s1, const char* s2);
class NoCase
{
public:
static bool compare(const string& x, const string& y);
};
class IniKeyInfo
{
public:
IniKeyInfo();
inline void SetSection(IniSectionInfo* pSection) { m_pSection = pSection; }
inline IniSectionInfo* GetSection() const { return m_pSection; }
inline string& KeyName() { return m_strKeyName; }
inline string& KeyValue() { return m_strKeyValue; }
inline string KeyNameEx() { return m_strKeyTrimLeft + m_strKeyName + m_strKeyTrimRight; }
inline string KeyValueEx() { return m_strValueTrimLeft + m_strKeyValue + m_strValueTrimRight; }
inline void SetLong(long lKeyValue) {ostringstream tempstream;tempstream << lKeyValue;m_strKeyValue=tempstream.str();/*ww m_strKeyValue.Format(("%d"), lKeyValue);*/ }
inline void SetULong(unsigned long ulKeyValue) { ostringstream tempstream;tempstream << ulKeyValue;m_strKeyValue=tempstream.str();/*m_strKeyValue.Format(("%u"), ulKeyValue);*/}
inline void SetHex(long lKeyValue) { ostringstream tempstream;tempstream << hex << lKeyValue;m_strKeyValue=tempstream.str();/*m_strKeyValue.Format(("%X"), lKeyValue);*/ }
inline void SetUHex(unsigned long ulKeyValue) {ostringstream tempstream;tempstream << hex << ulKeyValue;m_strKeyValue=tempstream.str();/* m_strKeyValue.Format(("%X"), ulKeyValue); */}
inline void SetDouble(double dblKeyValue) {ostringstream tempstream;tempstream << dblKeyValue;m_strKeyValue=tempstream.str();}
inline void SetString(const char* lpKeyValue) {ostringstream tempstream;tempstream << lpKeyValue;m_strKeyValue=tempstream.str(); /*m_strKeyValue = lpKeyValue; */}
void SetKeyName(const char* lpKeyName, bool bDoTrim = true);
void SetKeyValue(const char* lpKeyValue, bool bDoTrim = true);
void SetMultiLineString(const char* lpKeyValue);
long ToLong(long lDefault = 0);
unsigned long ToULong(unsigned long ulDefault = 0);
long ToHex(long lDefault = 0);
unsigned long ToUHex(unsigned long ulDefault = 0);
double ToDouble(double dblDefault = 0.0);
string ToString(const char* lpDefault = (""));
string ToMultiLineString(const char* lpDefault = (""));
inline string GetText(); //{ return m_strKeyName == ("")?m_strKeyValue:(m_strKeyName + ('=') + m_strKeyValue); }
inline string GetTextEx(); //{ return (m_strKeyName == (""))?((m_strKeyValue == (""))?(""):(("\r\n") + m_strKeyValue)):(("\r\n") + m_strKeyName + ('=') + m_strKeyValue); }
protected:
void TrimAndGetTrimValue(string& strSrc, string& strTrimLeft, string& strTrimRight);
const char* SplitStrP();
string& SplitStrR();
protected:
string m_strKeyName;
string m_strKeyValue;
string m_strKeyTrimLeft;
string m_strKeyTrimRight;
string m_strValueTrimLeft;
string m_strValueTrimRight;
//unsigned int m_uKeyNameLeftSpaceCount;
//unsigned int m_uKeyNameRightSpaceCount;
//unsigned int m_uKeyValueLeftSpaceCount;
//unsigned int m_uKeyValueRightSpaceCount;
IniSectionInfo* m_pSection;
};
typedef IniKeyInfo* PIniKeyInfo;
class IniSectionInfo : public WNCLoopList<IniKeyInfo>
{
public:
IniSectionInfo();
inline string& SectionName() { return m_strSectionName; }
inline void SetManager(IniFileManager* pManager) { m_pManager = pManager; }
inline IniFileManager* GetManager() { return m_pManager; }
inline PIniKeyInfo AddKey(const char* lpKeyName) { return GetKey(lpKeyName, true); }
PIniKeyInfo AddKey(const char* lpKeyName, const char* lpKeyValue, bool bReplace = true);
PIniKeyInfo AddKeyEx(const char* lpKeyName);
PIniKeyInfo AddKeyEx(const char* lpKeyName, const char* lpKeyValue);
PIniKeyInfo ParseData(const char* lpData, bool bReplace = true);
PIniKeyInfo ParseDataEx(const char* lpData);
PIniKeyInfo GetKey(const char* lpKeyName, bool bAdd = false);
long ToLong(const char* lpKeyName, long lDefault = 0);
unsigned long ToULong(const char* lpKeyName, unsigned long ulDefault = 0);
long ToHex(const char* lpKeyName, long lDefault = 0);
unsigned long ToUHex(const char* lpKeyName, unsigned long ulDefault = 0);
double ToDouble(const char* lpKeyName, double dblDefault = 0.0);
string ToString(const char* lpKeyName, const char* lpDefault = (""));
string ToMultiLineString(const char* lpKeyName, const char* lpDefault = (""));
inline void SetLong(const char* lpKeyName, long lKeyValue) { AddKey(lpKeyName)->SetLong(lKeyValue); }
inline void SetULong(const char* lpKeyName, unsigned long ulKeyValue) { AddKey(lpKeyName)->SetULong(ulKeyValue); }
inline void SetHex(const char* lpKeyName, long lKeyValue) { AddKey(lpKeyName)->SetHex(lKeyValue); }
inline void SetUHex(const char* lpKeyName, unsigned long ulKeyValue) { AddKey(lpKeyName)->SetUHex(ulKeyValue); }
inline void SetDouble(const char* lpKeyName, double dblKeyValue) { AddKey(lpKeyName)->SetDouble(dblKeyValue); }
inline void SetString(const char* lpKeyName, const char* lpKeyValue) { AddKey(lpKeyName)->SetString(lpKeyValue); }
inline void SetMultiLineString(const char* lpKeyName, const char* lpKeyValue) { AddKey(lpKeyName)->SetMultiLineString(lpKeyValue); }
string GetText();
string GetTextEx();
void JoinTo(IniSectionInfo& tarSection);
inline const char* SplitStrP();
inline string& SplitStrR();
protected:
string m_strSectionName;
IniFileManager* m_pManager;
};
typedef IniSectionInfo* PIniSectionInfo;
class IniFileManager : public WNCLoopList<IniSectionInfo>
{
public:
IniFileManager(bool bAutoSave = false);
virtual ~IniFileManager();
virtual inline PIniSectionInfo AddSection(const char* lpSectionName, bool bAdd = true) { return GetSection(lpSectionName, bAdd); }
virtual PIniSectionInfo AddSectionEx(const char* lpSectionName);
virtual PIniSectionInfo GetSection(const char* lpSectionName, bool bAdd = false);
virtual bool ParseSectionName(const char* lpData, string& strSectionName);
virtual PIniSectionInfo ParseLine(const char* lpData, bool* pbReplace = NULL);
virtual bool ParseData(const char* lpData, bool* pbReplace = NULL);
virtual bool ParseFile(const char* lpFileName, bool* pbReplace = NULL);
virtual bool SaveFile(const char* lpFileName = NULL, bool* pbUnicode = NULL);
virtual bool SaveFileEx(const char* lpFileName = NULL, bool* pbUnicode = NULL);
virtual long ToLong(const char* lpSectionName, const char* lpKeyName, long lDefault = 0);
virtual unsigned long ToULong(const char* lpSectionName, const char* lpKeyName, unsigned long ulDefault = 0);
virtual long ToHex(const char* lpSectionName, const char* lpKeyName, long lDefault = 0);
virtual unsigned long ToUHex(const char* lpSectionName, const char* lpKeyName, unsigned long ulDefault = 0);
virtual double ToDouble(const char* lpSectionName, const char* lpKeyName, double dblDefault = 0.0);
virtual string ToString(const char* lpSectionName, const char* lpKeyName, const char* lpDefault = (""));
virtual string ToMultiLineString(const char* lpSectionName, const char* lpKeyName, const char* lpDefault = (""));
virtual inline void SetLong(const char* lpSectionName, const char* lpKeyName, long lKeyValue) { AddSection(lpSectionName)->SetLong(lpKeyName, lKeyValue); }
virtual inline void SetULong(const char* lpSectionName, const char* lpKeyName, unsigned long ulKeyValue) { AddSection(lpSectionName)->SetULong(lpKeyName, ulKeyValue); }
virtual inline void SetHex(const char* lpSectionName, const char* lpKeyName, long lKeyValue) { AddSection(lpSectionName)->SetHex(lpKeyName, lKeyValue); }
virtual inline void SetUHex(const char* lpSectionName, const char* lpKeyName, unsigned long ulKeyValue) { AddSection(lpSectionName)->SetUHex(lpKeyName, ulKeyValue); }
virtual inline void SetDouble(const char* lpSectionName, const char* lpKeyName, double dblKeyValue) { AddSection(lpSectionName)->SetDouble(lpKeyName, dblKeyValue); }
virtual inline void SetString(const char* lpSectionName, const char* lpKeyName, const char* lpKeyValue) { AddSection(lpSectionName)->SetString(lpKeyName, lpKeyValue); }
virtual inline void SetMultiLineString(const char* lpSectionName, const char* lpKeyName, const char* lpKeyValue) { AddSection(lpSectionName)->SetMultiLineString(lpKeyName, lpKeyValue); }
virtual string GetText();
virtual string GetTextEx();
virtual void JoinTo(IniFileManager& tarIniManager);
virtual void SetAutoSave(bool bAutoSave);
virtual inline bool GetAutoSave() { return m_bAutoSave; }
//保存GetTextEx的结果
virtual void SaveState();
//判断文件内容是否改变
//带Ex的函数只检查mstrContentSaved与GetTextEx的内容是否相同
virtual bool DidStateChanged();
virtual bool DidStateChangedEx();
inline const char* SplitStrP();
inline string& SplitStrR();
protected:
string mstrIniFileName;
string mstrLineSplit; //行分割符,用于保存文件,解析数据时自动记录
bool m_bUnicode;
bool m_bAutoSave;
string mstrContentSaved;
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
//MD5ChecksumDefines.h : MD5 Checksum constants
//Magic initialization constants
#define MD5_INIT_STATE_0 0x67452301
#define MD5_INIT_STATE_1 0xefcdab89
#define MD5_INIT_STATE_2 0x98badcfe
#define MD5_INIT_STATE_3 0x10325476
//Constants for Transform routine.
#define MD5_S11 7
#define MD5_S12 12
#define MD5_S13 17
#define MD5_S14 22
#define MD5_S21 5
#define MD5_S22 9
#define MD5_S23 14
#define MD5_S24 20
#define MD5_S31 4
#define MD5_S32 11
#define MD5_S33 16
#define MD5_S34 23
#define MD5_S41 6
#define MD5_S42 10
#define MD5_S43 15
#define MD5_S44 21
//Transformation Constants - Round 1
#define MD5_T01 0xd76aa478 //Transformation Constant 1
#define MD5_T02 0xe8c7b756 //Transformation Constant 2
#define MD5_T03 0x242070db //Transformation Constant 3
#define MD5_T04 0xc1bdceee //Transformation Constant 4
#define MD5_T05 0xf57c0faf //Transformation Constant 5
#define MD5_T06 0x4787c62a //Transformation Constant 6
#define MD5_T07 0xa8304613 //Transformation Constant 7
#define MD5_T08 0xfd469501 //Transformation Constant 8
#define MD5_T09 0x698098d8 //Transformation Constant 9
#define MD5_T10 0x8b44f7af //Transformation Constant 10
#define MD5_T11 0xffff5bb1 //Transformation Constant 11
#define MD5_T12 0x895cd7be //Transformation Constant 12
#define MD5_T13 0x6b901122 //Transformation Constant 13
#define MD5_T14 0xfd987193 //Transformation Constant 14
#define MD5_T15 0xa679438e //Transformation Constant 15
#define MD5_T16 0x49b40821 //Transformation Constant 16
//Transformation Constants - Round 2
#define MD5_T17 0xf61e2562 //Transformation Constant 17
#define MD5_T18 0xc040b340 //Transformation Constant 18
#define MD5_T19 0x265e5a51 //Transformation Constant 19
#define MD5_T20 0xe9b6c7aa //Transformation Constant 20
#define MD5_T21 0xd62f105d //Transformation Constant 21
#define MD5_T22 0x02441453 //Transformation Constant 22
#define MD5_T23 0xd8a1e681 //Transformation Constant 23
#define MD5_T24 0xe7d3fbc8 //Transformation Constant 24
#define MD5_T25 0x21e1cde6 //Transformation Constant 25
#define MD5_T26 0xc33707d6 //Transformation Constant 26
#define MD5_T27 0xf4d50d87 //Transformation Constant 27
#define MD5_T28 0x455a14ed //Transformation Constant 28
#define MD5_T29 0xa9e3e905 //Transformation Constant 29
#define MD5_T30 0xfcefa3f8 //Transformation Constant 30
#define MD5_T31 0x676f02d9 //Transformation Constant 31
#define MD5_T32 0x8d2a4c8a //Transformation Constant 32
//Transformation Constants - Round 3
#define MD5_T33 0xfffa3942 //Transformation Constant 33
#define MD5_T34 0x8771f681 //Transformation Constant 34
#define MD5_T35 0x6d9d6122 //Transformation Constant 35
#define MD5_T36 0xfde5380c //Transformation Constant 36
#define MD5_T37 0xa4beea44 //Transformation Constant 37
#define MD5_T38 0x4bdecfa9 //Transformation Constant 38
#define MD5_T39 0xf6bb4b60 //Transformation Constant 39
#define MD5_T40 0xbebfbc70 //Transformation Constant 40
#define MD5_T41 0x289b7ec6 //Transformation Constant 41
#define MD5_T42 0xeaa127fa //Transformation Constant 42
#define MD5_T43 0xd4ef3085 //Transformation Constant 43
#define MD5_T44 0x04881d05 //Transformation Constant 44
#define MD5_T45 0xd9d4d039 //Transformation Constant 45
#define MD5_T46 0xe6db99e5 //Transformation Constant 46
#define MD5_T47 0x1fa27cf8 //Transformation Constant 47
#define MD5_T48 0xc4ac5665 //Transformation Constant 48
//Transformation Constants - Round 4
#define MD5_T49 0xf4292244 //Transformation Constant 49
#define MD5_T50 0x432aff97 //Transformation Constant 50
#define MD5_T51 0xab9423a7 //Transformation Constant 51
#define MD5_T52 0xfc93a039 //Transformation Constant 52
#define MD5_T53 0x655b59c3 //Transformation Constant 53
#define MD5_T54 0x8f0ccc92 //Transformation Constant 54
#define MD5_T55 0xffeff47d //Transformation Constant 55
#define MD5_T56 0x85845dd1 //Transformation Constant 56
#define MD5_T57 0x6fa87e4f //Transformation Constant 57
#define MD5_T58 0xfe2ce6e0 //Transformation Constant 58
#define MD5_T59 0xa3014314 //Transformation Constant 59
#define MD5_T60 0x4e0811a1 //Transformation Constant 60
#define MD5_T61 0xf7537e82 //Transformation Constant 61
#define MD5_T62 0xbd3af235 //Transformation Constant 62
#define MD5_T63 0x2ad7d2bb //Transformation Constant 63
#define MD5_T64 0xeb86d391 //Transformation Constant 64
//Null data (except for first BYTE) used to finalise the checksum calculation
static unsigned char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNBITINDEX_H
#define WNBITINDEX_H
#include "WNMemoryObjectManger.h"
class WNBitNode
{
public:
WNBitNode();
virtual ~WNBitNode();
//初始化
void ReInit();
//得到指定节点值(0-15)的子节点
WNBitNode* ChildNode(unsigned int uChildValue);
//得到指定节点值(0-15)的子节点的引用
WNBitNode*& ChildNodeRef(unsigned int uChildValue);
//添加子节点pNewNode
//如果pNewNode对应位置(pNewNode->muBitValue)的子节点已存在且bRemoveOldNode为false,则返回已有节点
//如果bRemoveOldNode为true则delete已有节点,同时返回NULL
//如果pNewNode与已存在的子节点相同则返回NULL
WNBitNode* AttatchChildNode(WNBitNode* pNewNode, bool bRemoveOldNode = true);
//分离指定节点值(0-15)的子节点
//返回已存在的节点,如指定节点不存在则返回NULL
WNBitNode* DetatchChildNode(unsigned int uChildValue);
//增加指定节点值(0-15)的子节点
//返回新增的节点
//如果节点已存在,则返回已有节点
WNBitNode* AddChildNode(unsigned int uChildValue);
//移除指定节点值(0-15)的子节点
void RemoveChildNode(unsigned int uChildValue);
//得到当前的节点的子节点数目
unsigned int LeafsCount();
//得到当前节点的子节点数目(包含数据)
unsigned int LeafsAndValueCount();
//获得当前节点所对应的数据
void* Data();
//获得当前节点所对应的数据的引用
void*& DataRef();
//设置当前节点所对应的数据为pNewData
//如果pNewData为NULL则删除当前节点所对应的数据的指针,此时如果mbIsWNObjectPtr为true则会旧数据进行Release操作
//如果bIsWNObject为true则会对新数据进行Retain操作
//返回旧数据,当旧数据(当前mbIsWNObjectPtr)为true时返回NULL
void* SetData(void* pNewData, bool bIsWNObject = false);
public:
static WNBitNode* NullPtr; //用于返回空引用
public:
unsigned long muLeafsInfo : 16; //叶子节点列表信息
unsigned int muNodeValue : 12; //当前节点所代表的值
bool mbHasData : 1; //当前节点是否有数值
bool mbIsWNObjectPtr : 1; //表示当前节点的数据是否是WNObject*类型的数据
//如果为true则析构或者调用SetData时会进行相关引用操作
bool mbIsEndBit : 1; //是否是一个字节的结束
bool mbDoNotFreeLeafs : 1; //是否在析构时delete所有的子节点,为true表示不delete
WNBitNode** mppLeafs; //叶子节点以及数据指针
};
class WNBitIndex
{
public:
typedef WNMemoryObjectManager<WNBitNode> NodeHeapManager;
public:
WNBitIndex();
virtual ~WNBitIndex();
//设置指定关键字的映射
//pKey是要设置的关键字,不能为NULL
//uKeyLen是关键字的长度,不能为0,单位是字节
//pData是与pKey关联的数据
//如果关键字已存在,则使用pData替换已存在的数据
//如果pData为NULL表示删除与pKey相关联的数据
//当pData以及pKey均不为NULL时返回与pKey相关联的旧数据(旧数据不存在返回NULL)
//如果旧数据是WNObject类型,返回NULL(参见WNBitNode类的SetData函数)
virtual void* SetItem(const void* pKey, unsigned int uKeyLen, void* pData, bool mbIsWNObject = false);
//获得与指定关键字相关联的数据
//pKey是指定的关键字,不能为NULL
//uKeyLen是关键字长度,不能为0,单位是字节
//返回值是与pKey相关联的数据,为NULL则表示数据不存在
virtual void* GetItem(const void* pKey, unsigned int uKeyLen);
//移除与指定关键字相关联的数据
//pKey是指定的关键字,不能为NULL
//uKeyLen是关键字长度,单位是字节
//返回值是与pKey相关联的数据,为NULL则表示数据不存在
virtual void* RemoveItem(const void* pKey, unsigned int uKeyLen);
//清空所有节点
virtual void ClearAll();
protected:
//查找与指定关键字相同的节点
//pKey是指定的关键字,不能为NULL
//uKeyLen是关键字长度,单位是字节
//返回值是与pKey相关联的节点
virtual WNBitNode* FindNode(const void* pKey, unsigned int uKeyLen);
//添加与指定关键字相同的节点(指定关键字的最后半个字节的节点)
//pKey是指定的关键字,不能为NULL
//uKeyLen是关键字长度,单位是字节
//返回值是与pKey相关联的节点,如果关键字节点不存在则添加
virtual WNBitNode* AddNode(const void* pKey, unsigned int uKeyLen);
protected:
WNBitNode* mpRoot[256]; //所有根节点,数组,下标从0-255
NodeHeapManager* mpNodeHeapManager; //所有中间节点的内存管理
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNBYTEBUFFER_H
#define WNBYTEBUFFER_H
#ifndef DEFAULT_BUFFER_SIZE
#define DEFAULT_BUFFER_SIZE 512
#endif
#include "WNCLoopList.h"
#include "WNObject.h"
class ByteBuffer
{
public:
ByteBuffer(unsigned long dwBufferSize = DEFAULT_BUFFER_SIZE);
ByteBuffer(void* pData, unsigned long dwSize);
ByteBuffer(ByteBuffer& srcByteBuffer);
virtual ~ByteBuffer();
bool InitBuffer(unsigned long dwBufferSize = DEFAULT_BUFFER_SIZE, bool bReserveData = false, bool bReservePos = false);
bool ReleaseBuffer();
unsigned long SetValidString(unsigned long dwStrLen);
unsigned long SetValidSize(unsigned long dwSize);
//bool ReadFile(FILE* pFile, unsigned long dwReadSize = 0);
bool ReadMemory(const void* pSrcData, unsigned long dwReadSize = 0);
unsigned long OutputWithPos(void* pTarData, unsigned long dwOutputSize = 0, const unsigned long* pdwPos = NULL);
unsigned long InputWithPos(const void* pSrcData, unsigned long dwInputSize = 0, const unsigned long* pdwPos = NULL );
bool operator == (const ByteBuffer& srcData);
bool operator == (const char* strSrc);
inline bool operator != (const char* strSrc) { return (*this == strSrc)?false:true; }
inline operator char* () { return (char*)m_pBuffer; }
inline operator unsigned char* () { return (unsigned char*)m_pBuffer; }
inline operator void* () { return (void*)m_pBuffer; }
ByteBuffer& operator = (const ByteBuffer& SrcByteBuffer);
inline ByteBuffer& operator = (const char* strData);
inline unsigned char& operator [] (unsigned long dwIndex) { return m_pBuffer[dwIndex]; }
inline unsigned long BufferSize() { return m_dwBufferSize; } //返回实际使用的缓冲区大小,真实缓冲区要比实际缓冲区多2个字节。
inline unsigned char* GetBuffer() { return m_pBuffer; }
inline unsigned char* GetPosBuffer() { return m_pPos; }
inline unsigned long GetPos() { return m_pPos - m_pBuffer; }
inline bool SetPos(unsigned long dwIndex) { return (dwIndex && (dwIndex < m_dwBufferSize))?((m_pPos = m_pBuffer+ dwIndex)?true:false):false; }
inline bool MovePos(long lOffset) { return SetPos(m_pPos + lOffset - m_pBuffer); }
inline void MovePosBegin() { m_pPos = m_pBuffer; }
inline char* GetString() { return (char*)m_pBuffer; }
inline char* GetPosString() { return (char*)m_pPos; }
inline unsigned long GetValidSize() { return m_dwValidSize; }
//bool SaveFile(const char* strFilename, bool bUseValidSize = true);
public:
unsigned long m_dwFlag;
protected:
unsigned char* m_pBuffer;
unsigned long m_dwBufferSize;
unsigned long m_dwValidSize;
unsigned char* m_pPos;
};
class WNByteBufferManager;
class WNByteBuffer : public ByteBuffer, public WNObject
{
public:
WNByteBuffer(unsigned long dwBufferSize = DEFAULT_BUFFER_SIZE);
public:
WNByteBufferManager* mpBufferManager;
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNBYTEBUFFERMANAGER_H
#define WNBYTEBUFFERMANAGER_H
#include "WNCreticalSection.h"
#include "WNCLoopList.h"
#include "WNByteBuffer.h"
#include "WNObject.h"
typedef WNCLoopList<WNByteBuffer> _WNByteBufferList;
class WNByteBufferList : public _WNByteBufferList
{
public:
WNByteBufferList();
public:
unsigned int muBufferSize;
};
#define DefMaxAllBufferSize 0x7FFFFFFF
#define DefMaxBufferCount 0x7FFFFFFF
#define DefMinBufferSize 1024
#define DefSetpBufferSize 1024
#define DefMaxBufferSize 1024*1024*10
class WNByteBufferManager : public WNCreticalSection, public WNObjectDelegate
{
public:
//构造函数
//uMinBufferSize表示缓冲区的最小大小
//uStepBufferSize表示每级缓冲区增加的大小
//uMaxBufferSize表示最大缓冲区大小
WNByteBufferManager(unsigned uMinBufferSize = DefMinBufferSize,
unsigned int uSetpBufferSize = DefSetpBufferSize,
unsigned int uMaxBufferSize = DefMaxBufferSize);
virtual ~WNByteBufferManager(void);
//初始化缓冲区管理器
void InitManager(unsigned int uMinBufferSize, unsigned int uStepBufferSize, unsigned int uMaxBufferSize);
//释放缓冲区管理器
void FreeManager();
//初始化指定大小以及数量的未使用的缓冲区
void InitBuffers(unsigned int uBufferSize, unsigned int uCount = 1);
//获得指定大小的未使用的自由缓冲区
//如果指定大小的缓冲区不存在则创建后返回
WNByteBuffer* GetBuffer(unsigned int uBufferSize, bool mbThreadSafeBuffer = false);
//释放缓冲区
void FreeBuffer(WNByteBuffer* pBuffer);
//设置自由缓冲区大小上限
void SetMaxAllBufferSize(unsigned int uSize);
//设置自由缓冲区数目上限
void SetMaxBufferCount(unsigned int uCount);
virtual bool OnWNObjectRetainCountIsZero(WNObject* pObject);
protected:
//根据指定的大小获得适合的缓冲区列表
WNByteBufferList* GetListByBufferSize(unsigned int uBufferSize);
public:
WNByteBufferList* mpBufferList; //自由缓冲区列表数组,下标0-muListCount,元素0保存不在[muMinBufferSize, muMaxBufferSize]范围内的缓冲区
unsigned int muListCount; //自由缓冲区列表数目
unsigned int muMinBufferSize; //最小缓冲区大小
unsigned int muStepBufferSize; //每一级增加的缓冲区大小
unsigned int muMaxBufferSize; //最大缓冲区大小
unsigned int muAllBufferSize; //所有缓冲区的大小
unsigned int muMaxAllBufferSize; //所有缓冲区的最大大小
unsigned int muAllBufferCount; //所有缓冲区的数目
unsigned int muMaxAllBufferCount; //所有缓冲区的最大数目
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef VNETMATELIST_H
#define VNETMATELIST_H
#include <unistd.h>
template <class T>
class WNCLoopListNode
{
public:
WNCLoopListNode() { prevNode = 0; nextNode = 0; };
WNCLoopListNode(const T& tValue) { prevNode = 0; nextNode = 0; data = tValue; }
T data;
WNCLoopListNode* prevNode;
WNCLoopListNode* nextNode;
};
template <class T>
class WNCLoopList
{
public:
typedef WNCLoopListNode<T> Node;
typedef Node* PNode;
WNCLoopList()
{
m_head = new Node;
m_head->prevNode = m_head;
m_head->nextNode = m_head;
m_begin = m_head;
m_end = m_head;
m_current = m_head;
m_dwCount = 0;
}
WNCLoopList(const WNCLoopList<T>& list)
{
m_head = new Node;
m_head->prevNode = m_head;
m_head->nextNode = m_head;
m_begin = m_head;
m_end = m_head;
m_current = m_head;
m_dwCount = 0;
*this = list;
}
WNCLoopList<T>& operator = (const WNCLoopList<T>& list)
{
ClearList();
for (WNCLoopList<T>::PNode pNode = list.Begin(); pNode != list.Head(); pNode = pNode->nextNode)
{
AppendNode(pNode->data);
}
return *this;
}
virtual ~WNCLoopList()
{
ClearList();
if (m_head)
{
delete m_head;
m_head = 0;
}
m_begin = 0;
m_end = 0;
m_current = 0;
m_dwCount = 0;
}
inline PNode Head() const { return m_head; }
inline PNode Begin() const { return m_begin; }
inline PNode End() const { return m_end; }
inline PNode Current() const { return m_current; }
inline PNode MoveBegin() { return m_current = m_begin; }
inline PNode MoveEnd() { return m_current = m_end; }
inline PNode MovePrev() { return m_current = m_current->prevNode; }
inline PNode MoveNext() { return m_current = m_current->nextNode; }
inline unsigned long ListCount() const { return m_dwCount; }
inline T& HeadData() const { return m_head->data; }
inline T& BeginData() const { return m_begin->data; }
inline T& EndData() const { return m_end->data; }
inline T& CurrentData() const { return m_current->data; }
inline bool NotHead() const { return m_current != m_head; }
PNode Item(unsigned long dwIndex) const
{
PNode pNode = m_head;
while (dwIndex)
{
pNode = pNode->nextNode;
dwIndex--;
}
return pNode;
}
inline T& operator [] (unsigned long dwIndex) const
{
return Item(dwIndex)->data;
}
bool FindNode(PNode pFindNode) const
{
for (PNode pNode = m_begin; pNode != m_head; pNode = pNode.nextNode)
{
if (pNode == pFindNode)
{
return true;
}
}
return false;
}
PNode FindData(T& data) const
{
for (PNode pNode = m_begin; pNode != m_head; pNode = pNode->nextNode)
{
if (pNode->data == data)
{
return pNode;
}
}
return 0;
}
PNode AppendNode(const Node& node, PNode pPrevNode = 0)
{
PNode pNode = (PNode)&node;
if (!pNode)
{
return 0;
}
if (!pPrevNode)
{
pPrevNode = m_end;
}
PNode pNewNode = new Node(*pNode);
pNewNode->nextNode = pPrevNode->nextNode;
pPrevNode->nextNode->prevNode = pNewNode;
pPrevNode->nextNode = pNewNode;
pNewNode->prevNode = pPrevNode;
if (pNewNode->prevNode == m_head)
{
m_begin = pNewNode;
}
if (pNewNode->nextNode == m_head)
{
m_end = pNewNode;
}
m_dwCount++;
return pNewNode;
}
PNode AppendNode(PNode pNode, PNode pPrevNode = 0)
{
if (!pNode)
{
return 0;
}
if (!pPrevNode)
{
pPrevNode = m_end;
}
PNode pNewNode = pNode;
pNewNode->nextNode = pPrevNode->nextNode;
pPrevNode->nextNode->prevNode = pNewNode;
pPrevNode->nextNode = pNewNode;
pNewNode->prevNode = pPrevNode;
if (pNewNode->prevNode == m_head)
{
m_begin = pNewNode;
}
if (pNewNode->nextNode == m_head)
{
m_end = pNewNode;
}
m_dwCount++;
return pNewNode;
}
PNode AppendNode(T& data, PNode pPreNode = 0)
{
PNode pNode = new Node;
pNode->data = data;
return AppendNode(pNode, pPreNode);
}
PNode PreAppendNode(const Node& node, PNode pNextNode = 0)
{
PNode pNode = (PNode)&node;
if (!pNode)
{
return NULL;
}
if (!pNextNode)
{
pNextNode = m_begin;
}
PNode pNewNode = new Node(*pNode);
pNewNode->prevNode = pNextNode->prevNode;
pNextNode->prevNode->nextNode = pNewNode;
pNewNode->nextNode = pNextNode;
pNextNode->prevNode = pNewNode;
if (pNewNode->prevNode == m_head)
{
m_begin = pNewNode;
}
if (pNewNode->nextNode == m_head)
{
m_end = pNewNode;
}
m_dwCount++;
return pNewNode;
}
PNode PreAppendNode(PNode pNode, PNode pNextNode = 0)
{
if (!pNode)
{
return NULL;
}
if (!pNextNode)
{
pNextNode = m_begin;
}
PNode pNewNode = pNode;
pNewNode->prevNode = pNextNode->prevNode;
pNextNode->prevNode->nextNode = pNewNode;
pNewNode->nextNode = pNextNode;
pNextNode->prevNode = pNewNode;
if (pNewNode->prevNode == m_head)
{
m_begin = pNewNode;
}
if (pNewNode->nextNode == m_head)
{
m_end = pNewNode;
}
m_dwCount++;
return pNewNode;
}
PNode PreAppendNode(T& data, PNode pNextNode = 0)
{
PNode pNode = new Node;
pNode->data = data;
return PreAppendNode(pNode, pNextNode);
}
PNode DetachNode(PNode pNode = 0)
{
if (!pNode)
{
pNode = m_current;
}
if (pNode == m_head)
{
return 0;
}
if (m_current == pNode)
{
if (m_current == m_end)
{
m_current = pNode->prevNode;
}
else
{
m_current = pNode->nextNode;
}
}
pNode->prevNode->nextNode = pNode->nextNode;
if (m_end == pNode)
{
m_end = pNode->prevNode;
}
pNode->nextNode->prevNode = pNode->prevNode;
if (m_begin == pNode)
{
m_begin = pNode->nextNode;
}
pNode->prevNode= NULL;
pNode->nextNode = NULL;
m_dwCount--;
return pNode;
}
PNode RemoveNode(PNode pNode = 0)
{
if (!pNode)
{
pNode = m_current;
}
if (pNode == m_head)
{
return m_head;
}
PNode retNode = 0;
if (m_current == pNode)
{
if (m_current == m_end)
{
m_current = pNode->prevNode;
}
else
{
m_current = pNode->nextNode;
}
retNode = m_current;
}
else
{
if (pNode == m_end)
{
retNode = pNode->prevNode;
}
else
{
retNode = pNode->nextNode;
}
}
pNode->prevNode->nextNode = pNode->nextNode;
if (m_end == pNode)
{
m_end = pNode->prevNode;
}
pNode->nextNode->prevNode = pNode->prevNode;
if (m_begin == pNode)
{
m_begin = pNode->nextNode;
}
delete pNode;
m_dwCount--;
return retNode;
}
virtual void ClearList()
{
for (MoveBegin(); Current() != Head(); )
{
RemoveNode();
}
m_begin = m_head;
m_end = m_head;
m_current = m_head;
m_dwCount = 0;
}
protected:
PNode m_head;
PNode m_begin;
PNode m_end;
PNode m_current;
unsigned long m_dwCount;
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef STRINGLIST_H
#define STRINGLIST_H
#include "WNCLoopList.h"
#include <string>
using namespace std;
class WNCStringList:public WNCLoopList<string>
{
public:
WNCStringList() { };
~WNCStringList() { };
WNCStringList(const char* lpStringList, const char* lpSplit = "|");
WNCStringList(const string& strStringList, const string& strSplit = "|");
virtual void CreateList(const char* lpStringList = "", const char* lpSplit = "|");
virtual void CreateList(const string& strStringList = string(""), const string& strSplit = string("|"));
string Join(const char* lpSplit = "|");
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNCOMMONSOCKET_H
#define WNCOMMONSOCKET_H
//#include "ACCallback.h"
#include "WNCommonSocketDelegate.h"
#include "WNSocketObserver.h"
#include "WNWorkThread.h"
#include <sys/socket.h>
#include <string>
using namespace std;
#ifndef WIN32
# ifndef WINTYPEDEF
# define WINTYPEDEF
typedef bool BOOL;
#define TRUE true
#define FALSE false
typedef unsigned short USHORT;
typedef const char* LPCTSTR;
typedef unsigned int UINT;
typedef int INT;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
typedef unsigned int DWORD;
typedef string CString;
typedef void* HWND;
#define LRESULT long
#define CALLBACK
#define WINAPI
#define _tcstoul strtoul
#define _T(str) str
typedef long LONG;
typedef LONG WPARAM;
typedef LONG LPARAM;
typedef void* LPVOID;
typedef void* HANDLE;
typedef void* ACWinProc;
typedef int SOCKET;
# endif
#endif
class WNCommonSocket
: public WNSocketObserverTarget
, public WNSocketObserverTargetDelegate
, public WNWorkThreadDelegate
{
#ifdef WIN32
typedef LRESULT (WNCommonSocket::*ACWindowHookProc)(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
typedef ACCallback<WNDPROC, WNCommonSocket, WNCommonSocket::ACWindowHookProc> ACWinProc;
#endif
public:
WNCommonSocket(void);
virtual ~WNCommonSocket(void);
virtual BOOL CreateSocket();
virtual BOOL SetSocketAddress(LPCTSTR lpAddress);
virtual BOOL SetSocketAddress(LPCTSTR lpAddress, UINT uPort);
virtual BOOL SetSocketAddress(SOCKADDR* pSockAddr);
virtual BOOL EnterObserverLoop(BOOL bInNewThread);
virtual BOOL ExitObserverLoop();
virtual void CloseSocket();
virtual BOOL AcceptSocket(WNCommonSocket* pNewSocket, SOCKADDR* pSockAddr = NULL, int* pSockAddrLen = NULL);
virtual BOOL AcceptSocket(WNCommonSocket& newSocket, CString* pstrSockAddr = NULL, int* pSockAddrLen = NULL);
virtual BOOL ConnectSocket(LPCTSTR lpszHostAddress);
virtual BOOL ConnectSocket(SOCKADDR* pHostAddress);
virtual BOOL IOCtl(long lCommand, DWORD* lpArgument);
virtual BOOL SetSockOpt(int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel = SOL_SOCKET);
virtual BOOL GetSockOpt(int nOptionName, void* lpOptionValue,int* lpOptionLen, int nLevel = SOL_SOCKET);
virtual BOOL Listen(int nConnectionBacklog);
virtual BOOL GetPeerName(CString& strIp, UINT& uPort);
virtual BOOL GetPeerName(SOCKADDR* lpSockAddr, int* lpSockAddrLen);
virtual BOOL GetSockName(CString& strIp, UINT& uPort);
virtual BOOL GetSockName(SOCKADDR* lpSockAddr, int* lpSockAddrLen);
virtual void SetReceiveBuffer(void* pBuffer, UINT uBufferLen);
virtual DWORD ReceivedDataLen();
virtual int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
virtual int ReceiveFrom(void* lpBuf, int nBufLen, CString& rSocketAddress, int nFlags = 0);
virtual int ReceiveFrom(void* lpBuf, int nBufLen, SOCKADDR* pSocketAddress, int* pSockAddrLen, int nFlags = 0);
virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
virtual int SendTo(const void* lpBuf, int nBufLen, LPCTSTR lpSocketAddress, int nFlags = 0);
virtual int SendTo(const void* lpBuf, int nBufLen, SOCKADDR* pSocketAddress, int nFlags = 0);
static SOCKADDR Ipv4StringToData(LPCTSTR lpAddress);
static BOOL Ipv4StringToData(LPCTSTR lpAddress, SOCKADDR& addrData);
static CString Ipv4DataToString(SOCKADDR& addrIn, BOOL bWithPort);
static BOOL Ipv4DataToString(SOCKADDR& addrIn, CString& strAddr, BOOL bWithPort);
static int GetLastError();
virtual bool OnWorkThreadProc(WNWorkThread* objThread, unsigned int& uStep);
virtual unsigned int OnWorkThreadNeedSleep(WNWorkThread* objThread);
protected:
virtual BOOL CreateSocketWindow();
virtual BOOL DestroySocketWindow();
virtual LRESULT InternalWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT ACWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static DWORD WINAPI RunLoopThreadProc(LPVOID lpParameter);
DWORD InternalRunLoopThreadProc();
//当前socket可读(或可以进行accept操作)
virtual void OnObserverRead(IWNSocketObserver* observer);
//当前socket错误
virtual void OnObserverError(IWNSocketObserver* observer);
virtual BOOL DoPorcessTcpDataRead();
virtual BOOL DoProcessUdpDataRead();
virtual BOOL DoProcessObserverRead(IWNSocketObserver* observer);
virtual BOOL DoProcessObserverError(IWNSocketObserver* observer);
#ifndef WIN32
friend LRESULT CALLBACK WNCommonSocketWindowProcedure (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
public:
HWND mhwnd; //socket相关窗口,在非当前线程中创建socket时有效
DWORD mdwWindowThreadId; //窗口线程id
//BOOL mbHasWindowMessage; //表示是否有窗口消息未处理/
HANDLE mThreadHandle; //线程句柄
DWORD mdwThreadId; //线程id
WNWorkThread* mpRunLoopThread; //工作线程
UINT muRunLoopThreadSleepTime; //工作线程睡眠时间,毫秒
INT miSocketInitProtocalFamily; //初始化用的socket协议族,默认为AF_INET
INT miSocketInitType; //初始化用的socket类型,默认为SOCK_STREAM
INT miSocketInitProtocal; //初始化用的协议,默认为0
BOOL mbExitThread; //退出线程标志位
BOOL mbIsThreadRunning; //表示线程是否正在运行
WNCommonSocketDelegate* mpCommonSocketDelegate; //托管对象
CString mstrSocketIdentity; //socket标识符
void* mUserInfo; //用户信息
ACWinProc* mpACWinProc; //窗口处理函数回调
#ifdef WIN32
UINT muMsgOnWNObserverRead; //检测到socket可读
UINT muMsgOnWNObserverError; //检测到socket错误
UINT muMsgNeedDestroyWindow; //需要销毁窗口消消息
#endif
char* mpReceiveBuffer; //接收缓冲区
char* mpReceiveBufferPos; //当前接收位置
UINT muAvailableReceiveLen; //接收缓冲区可用大小
volatile BOOL mbOnRead;
volatile BOOL mbOnError;
volatile IWNSocketObserver* mpReadObserver;
volatile IWNSocketObserver* mpErrorObserver;
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNCOMMONSOCKETDELEGATE_H
#define WNCOMMONSOCKETDELEGATE_H
class WNCommonSocket;
class WNCommonSocketDelegate
{
public:
//可以进行Accept连接
virtual void OnCommonSocketAccept(WNCommonSocket* sock) { }
//远程socket已关闭
virtual void OnCommonSocketClose(WNCommonSocket* sock) { }
//有错误发生
virtual void OnCommonSocketError(WNCommonSocket* sock, int iErrorCode) { }
//有数据可以接收
virtual void OnCommonSocketReceive(WNCommonSocket* sock, unsigned int uUnreadDataLen) { }
//提示接收缓冲区已满
//仅仅在socket的类型为SOCK_STREAM(tcp)时有效
virtual void OnCommonSocketRecvBufferFulled(WNCommonSocket* sock, void* pBuffer, unsigned int uBufferLen, unsigned int uUnreadDataLen) { }
virtual bool OnCommonSocketThreadProc(unsigned int* uSleepTime) { return true; }
virtual ~WNCommonSocketDelegate(){}
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNCRETICALSECTION_H
#define WNCRETICALSECTION_H
#include <pthread.h>
class WNCreticalSection
{
public:
WNCreticalSection(void);
virtual ~WNCreticalSection(void);
virtual void CreateLocker();
virtual void DestroyLocker();
virtual bool TryLock();
virtual bool Lock();
virtual bool Unlock();
protected:
//wlf CRITICAL_SECTION* mpLocker;
pthread_mutex_t* mpLocker;
};
//自动解锁,仅在同一函数中定义以及使用
class WNCreticalSectionAutoLocker
{
public:
WNCreticalSectionAutoLocker();
WNCreticalSectionAutoLocker(WNCreticalSection* pCreiticalSection, bool bLocker = true);
virtual ~WNCreticalSectionAutoLocker();
virtual bool TryLock();
virtual void Lock();
virtual void Unlock();
public:
WNCreticalSection* mpLocker;
WNCreticalSection* mpLocking;
};
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNDECOD_H
#define WNDECOD_H
class WNByteBuffer;
typedef struct _WNFrameInfo
{
unsigned int uUserInfo[2]; //包类型
unsigned int uHeader; //头标记
unsigned int uVersion; //版本号
unsigned int uSize; //数据长度
unsigned int uType; //数据包类型
unsigned int uStreamID; //数据流ID,
unsigned int uTimeStamp; //时间戳
} WNFrameInfo, *PWNFrameInfo;
typedef struct _WNDecodedFrameInfo
{
unsigned int uUserInfo[2];
unsigned int uDataFormat; //数据格式
unsigned int uWidth; //宽度
unsigned int uHeight; //高度
unsigned int uSize; //数据大小
unsigned int uStreamID; //数据流ID
unsigned int uTimeStamp; //时间戳
} WNDecodedFrameInfo, *PWNDecodedFrameInfo;
typedef const char* WNDecoderName;
class WNDecoder;
class WNDecoderDelegate
{
public:
virtual ~WNDecoderDelegate() { }
virtual void OnNetworkVideoDeviceDecoded(WNDecoder* pDevice) { }
};
class WNDecoder
{
public:
//托管对象,非空时通过此对象回调WNDecoderDelegate的接口
WNDecoderDelegate* mpDecoderDelegate;
public:
WNDecoder() { mpDecoderDelegate = 0; }
virtual ~WNDecoder() { mpDecoderDelegate = 0; }
//返回解码器名称
virtual WNDecoderName DecoderName() = 0;
//初始化解码器
//成功返回true,识别返回false
virtual bool InitDecoder() = 0;
//解码器开始工作
//成功返回true,识别返回false
virtual bool StartWork() =0;
//解码器停止工作
//成功返回true,识别返回false
virtual bool EndWork() = 0;
//解码pFrameBuffer
//pInfo是pFrameBuffer的相关信息
//成功返回true,失败返回false
virtual bool DoDecode(WNByteBuffer* pFrameBuffer, WNFrameInfo* pInfo = 0) = 0;
//获得最后一次解码成功的帧(解码后的数据)
//返回的帧在调用FreeDecodedFrame之前当前解码器不允许使用
//[输出] pInfo是解码后帧的信息指针。
//[输入] bSafeCall表示是否是安全调用。
//安全调用是指在托管对象的OnNetworkVideoDeviceDecoded被调用的时候在同一线程中调用本函数
//安全调用时无需加锁
//注意,对同一WNDecoder对象只能选择一种方式调用本函数,或者安全调用,或者非安装调用
virtual void* GetNextDecodedFrame(WNDecodedFrameInfo* pInfo = 0, bool bSafeCall = true) = 0;
//释放通过GetNextDecodedFrame获得的解码后的数据
//释放后的数据可以被当前解码器使用
virtual void FreeDecodedFrame(void* pDecodedFrame) = 0;
};
//通过默认的消息中心创建解码器
//发送:
// 参数1设置为要创建的解码器名称指针(WNDecoderName类型)
// 参数2设置为0
//返回(调用完毕后):
// 参数1不变
// 参数2设置为创建的解码器指针,继承WNDecoder
#define NT_CreateDecoder "NT_CreateDecoder"
//通过默认的消息中心销毁解码器
//发送:
// 参数1设置为要销毁的解码器名称指针(WNDecoderName类型)
// 参数2设置为要销毁的解码器指针
//返回(调用完毕后):
// 参数1不变
// 参数2设置为0,表示销毁成功,继承WNDecoder
#define NT_DestroyDecoder "NT_DestroyDecoder"
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNINVOKER_H
#define WNINVOKER_H
#include "ACCallback.h"
#include "WNObject.h"
#include "WNReadWriteLocker.h"
#include "WNCLoopList.h"
#include <sys/time.h>
extern long getCurrentTime();
class WNInvokeInfo : public WNObject
{
public:
WNInvokeInfo();
~WNInvokeInfo();
virtual void InvokeMemberFunc() { return; }
virtual void Reset();
public:
BOOL mbInvoked;
UINT muInvokeTime;
void* mpReturnValue;
};
typedef void (*StdInvokeMemberFuncVoid)();
template <typename _TClass, typename _TPMemberFunc>
class InvokeMemberFuncVoidInfo : public WNInvokeInfo
{
public:
virtual void InvokeMemberFunc()
{
mCallBack.mpStdFunc();
mbInvoked = TRUE;
}
virtual void Reset()
{
mCallBack.FreeCode();
WNInvokeInfo::Reset();
}
public:
ACCallbackEx<StdInvokeMemberFuncVoid> mCallBack;
};
typedef void (*StdInvokeMemberFuncVoidWNObject)(WNObject*);
template <typename _TClass, typename _TPMemberFunc>
class InvokeMemberFuncVoidWNObjectInfo : public WNInvokeInfo
{
public:
InvokeMemberFuncVoidWNObjectInfo()
{
mpParam = NULL;
}
virtual void InvokeMemberFunc()
{
mCallBack.mpStdFunc(mpParam);
mbInvoked = TRUE;
}
virtual void Reset()
{
doRelease(mpParam);
WNInvokeInfo::Reset();
}
public:
ACCallbackEx<StdInvokeMemberFuncVoidWNObject> mCallBack;
WNObject* mpParam;
};
class WNInvoker
{
public:
virtual ~WNInvoker();
//执行类对象的成员函数
//支持的成员函数形式为void Class::MemberFunc();
//pObject是要执行成员函数的对象
// 请注意保证在函数被执行前pObject不要被销毁
//pMemberFunc是成员函数指针
//pParam是要执行的成员函数参数
//uAfterDelay表示执行的延迟,为0表示在执行线程的下一个循环中执行
//返回值为执行信息
template <typename _TClass, typename _TPMemberFunc>
WNInvokeInfo* InvokeMemberFuncVoid(_TClass* pObject, _TPMemberFunc pMemberFunc, UINT uAfterDelay = 0)
{
InvokeMemberFuncVoidInfo<_TClass, _TPMemberFunc>* pInvokeInfo = _WNSafeAlloc<InvokeMemberFuncVoidInfo<_TClass, _TPMemberFunc> >();
pInvokeInfo->Retain();
pInvokeInfo->mCallBack.SetCallBackMemberFunc(pObject, pMemberFunc);
pInvokeInfo->muInvokeTime = getCurrentTime() + uAfterDelay;
AddInvokeInfo(pInvokeInfo);
return pInvokeInfo;
}
//执行类对象的成员函数
//支持的成员函数形式为void Class::MemberFunc(WNObject*);
//pObject是要执行成员函数的对象
// 请注意保证在函数被执行前pObject不要被销毁
//pMemberFunc是成员函数指针
//pParam是要执行的成员函数参数
//uAfterDelay表示执行的延迟,为0表示在执行线程的下一个循环中执行
////返回值为执行信息
template <typename _TClass, typename _TPMemberFunc>
WNInvokeInfo* InvokeMemberFuncVoidWNObject(_TClass* pObject, _TPMemberFunc pMemberFunc, WNObject* pParam = NULL, UINT uAfterDelay = 0)
{
InvokeMemberFuncVoidWNObjectInfo<_TClass, _TPMemberFunc>* pInvokeInfo = _WNSafeAlloc<InvokeMemberFuncVoidWNObjectInfo<_TClass, _TPMemberFunc> >();
pInvokeInfo->Retain();
pInvokeInfo->mCallBack.SetCallBackMemberFunc(pObject, pMemberFunc);
if (pParam)
{
pInvokeInfo->mpParam = pParam->Retain();
}
pInvokeInfo->muInvokeTime = getCurrentTime() + uAfterDelay;
AddInvokeInfo(pInvokeInfo);
return pInvokeInfo;
}
virtual void AddInvokeInfo(WNInvokeInfo* pInvokeInfo);
//检查执行队列中是否有需要执行的函数
//如果有则执行所有的函数
//返回是否有执行函数
virtual BOOL DoCheckAndInvoke();
//检查执行队列中是否有需要执行的函数
//如果队列中有需要执行的函数则返回TRUE,否则返回FALSE
virtual BOOL DoCheckInvoke();
//调用执行队列中的函数
//只做一次调用
//如果执行了函数返回TRUE,否则返回FALSE
virtual BOOL DoInvoke();
public:
WNCLoopList<WNInvokeInfo*> mInvokeList;
WNReadWriteLocker mInvokeLocker;
};
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef MEMORYOBJECTMANAGER_H
#define MEMORYOBJECTMANAGER_H
#include "WNCLoopList.h"
template <class T>
class WNMemoryObject
{
public:
WNMemoryObject() { m_pPrevObject = NULL; m_pNextObject = NULL; }
public:
T m_Object;
WNMemoryObject* m_pPrevObject;
WNMemoryObject* m_pNextObject;
};
template <class T>
class WNMemoryObjectManager
{
public:
typedef WNMemoryObject<T> Node;
typedef Node* PNode;
typedef WNCLoopList<PNode> MemoryBlocks;
public:
WNMemoryObjectManager(unsigned long dwBlockSize = 1024)
{
m_dwBlockSize = dwBlockSize;
m_FreeObjectHead.m_pNextObject = &m_FreeObjectHead;
m_FreeObjectHead.m_pPrevObject = &m_FreeObjectHead;
m_dwFreeCount = 0;
m_UsedObjectHead.m_pNextObject = &m_UsedObjectHead;
m_UsedObjectHead.m_pPrevObject = &m_UsedObjectHead;
m_dwUsedCount = 0;
AllocMemoryBlock();
}
virtual ~WNMemoryObjectManager()
{
for (m_MemoryBlocks.MoveBegin(); m_MemoryBlocks.NotHead(); m_MemoryBlocks.MoveNext())
{
delete[] m_MemoryBlocks.CurrentData();
}
}
//从自由区分配对象指针,返回的对象指针未经过初始化
virtual T* AllocObject()
{
if (!m_dwFreeCount)
{
AllocMemoryBlock();
}
if (!m_dwFreeCount)
{
return NULL;
}
PNode pNode = m_FreeObjectHead.m_pNextObject;
//将节点从自由区移入已使用区
m_FreeObjectHead.m_pNextObject = pNode->m_pNextObject;
pNode->m_pNextObject->m_pPrevObject = &m_FreeObjectHead;
m_dwFreeCount--;
m_UsedObjectHead.m_pPrevObject->m_pNextObject = pNode;
pNode->m_pPrevObject = m_UsedObjectHead.m_pPrevObject;
m_UsedObjectHead.m_pPrevObject = pNode;
pNode->m_pNextObject = &m_UsedObjectHead;
m_dwUsedCount--;
return (T*)pNode;
}
//将对象指针从使用区放入自由区,pObject必须为从AllocObject函数分配的对象指针
virtual void FreeObject(T* pObject)
{
PNode pNode = (PNode)pObject;
//将节点从使用区移入自由区
pNode->m_pPrevObject->m_pNextObject = pNode->m_pNextObject;
pNode->m_pNextObject->m_pPrevObject = pNode->m_pPrevObject;
m_dwUsedCount--;
m_FreeObjectHead.m_pPrevObject->m_pNextObject = pNode;
pNode->m_pPrevObject = m_FreeObjectHead.m_pPrevObject;
m_FreeObjectHead.m_pPrevObject = pNode;
pNode->m_pNextObject = &m_FreeObjectHead;
m_dwFreeCount++;
}
protected:
virtual bool AllocMemoryBlock()
{
if (!m_dwBlockSize)
{
return false;
}
PNode pBlock = new Node[m_dwBlockSize];
if (!pBlock)
{
return false;
}
//将内存块放入内存块列表
m_MemoryBlocks.AppendNode(pBlock);
//将所有区块相连
for (unsigned long i = 0; i < m_dwBlockSize; i++ )
{
pBlock[i].m_pPrevObject = pBlock + i - 1;
pBlock[i].m_pNextObject = pBlock + i + 1;
}
//将区块加入自由区
m_FreeObjectHead.m_pPrevObject->m_pNextObject = pBlock;
pBlock->m_pPrevObject = m_FreeObjectHead.m_pPrevObject->m_pNextObject;
m_FreeObjectHead.m_pPrevObject = &pBlock[m_dwBlockSize - 1];
pBlock[m_dwBlockSize -1 ].m_pNextObject = &m_FreeObjectHead;
m_dwFreeCount += m_dwBlockSize;
return true;
}
protected:
MemoryBlocks m_MemoryBlocks;
Node m_FreeObjectHead;
Node m_UsedObjectHead;
unsigned long m_dwBlockSize;
unsigned long m_dwFreeCount;
unsigned long m_dwUsedCount;
};
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef SYSTEMIDNUMBER_H
#define SYSTEMIDNUMBER_H
#pragma once
#pragma comment(lib, "Iphlpapi")
#include "Iphlpapi.h"
#include "EBaseFunctions.h"
//#include "CSWbemServices.h"
//#include "CSWbemObject.h"
//#include "CSWbemObjectSet.h"
//#include "CSWbemLocator.h"
#define MAC_LENGTH 20
#define ADAPTER_COUNT_MAX 20
class WNAddrData
{
public:
WNAddrData();
WNAddrData(const WNAddrData& data);
CString GetMacAddress();
inline BOOL IsVirtual() { return m_bIsVirtual; }
WNAddrData& operator=(const WNAddrData& data);
public:
DWORD m_dwAdapterIndex;
CString m_strAdapterName;
CString m_strAdapterInfo;
CString m_strIp;
CString m_strSubnetMask;
CString m_strBroadCastIp;
UINT m_uMacLen;
BYTE m_MacAddr[MAC_LENGTH];
CString m_strVirtualMac;
BOOL m_bIsVirtual;
UINT m_uType;
CString m_strIPList[256];
UINT m_nIPCount;
DWORD m_dwStartIp;
DWORD m_dwEndIp;
};
class WNNetworkInfo
{
public:
WNNetworkInfo();
//get mac address,return the number of mac address
LONG GetCount() { return m_lCount; }
WNAddrData* GetAdapterInfo(LONG lIndex);
VOID ReInit();
VOID SetVirtualMac(CString& strMac);
void OutputAdapterInfo();
static BOOL IsConnectedAdapter(DWORD dwAdapterIndex);
protected:
LONG GetSystemMacInfo(WNAddrData* pMacData);
private:
WNAddrData m_AddrData[100];
LONG m_lCount;
};
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNNOTIFICATIONCENTER_H
#define WNNOTIFICATIONCENTER_H
#include "WNObject.h"
#include "WNCLoopList.h"
#include <string>
using namespace std;
class WNNotificationCenter;
class WNReadWriteLocker;
class WNCreticalSection;
//默认2个参数,可以重定义此宏,但是此宏不能为0
//重定义此宏时,在包含WNNotificationCenter.h之前定义
#ifndef DEF_NT_PARAMS_COUNT
#define DEF_NT_PARAMS_COUNT 3
#endif
//通知消息类
class WNNotification : public WNObject
{
public:
WNNotification(unsigned int muParamsCount = DEF_NT_PARAMS_COUNT);
virtual ~WNNotification();
//通知名称
virtual const char* NotificationName();
//判断通知名称是否为指定名称
virtual bool IsNotification(const char* lpNotificationName);
//获得整个通知的大小
virtual unsigned int GetSize();
//获得整个通知的拷贝
//返回值需要通过Release释放
//未实现
virtual WNNotification* GetCopy();
//拷贝内容至pNotification
//未实现
virtual void CopyTo(WNNotification* pNotification);
public:
unsigned int muNotificationId; //通知Id
void* mpNotificationSender; //通知发送者
WNObject* mpNotificationData; //通知数据
WNNotificationCenter* mpNotificationCenter; //投递消息的消息中心
unsigned int muParamsCount; //参数个数
unsigned int mParams[DEF_NT_PARAMS_COUNT]; //参数列表
};
//通知接受者类
class WNNotificationReceiver
{
public:
//通知回调
virtual void OnReceiveNotification(WNNotification* pNotification) { }
virtual void OnReceiveNotification(WNNotification *pNotification, void* pThread) { }
virtual ~WNNotificationReceiver(){}
};
class WNWorkThread;
//通知观察者类
class WNNotificationObserver : public WNNotificationReceiver
{
public:
virtual ~WNNotificationObserver(){}
//开始观察指定发送者以及消息中心的通知(字符串)
//lpNotificationName是要观察的通知名称
//pSender是发送者,为NULL时表示观察所有发送者发送的lpNotificationName
//pNotification是指定的消息中心,为默认值NULL是表示使用WNNotificationCenter::DefaultCenter()
//返回值为通知Id,返回值为非0表示成功,否则表示失败
virtual unsigned int StartObserveNotification(const char* lpNotificationName, void* pSender = NULL, WNNotificationCenter* pNotificationCenter = NULL);
//停止观察指定发送者以及消息中心的通知(字符串)
//lpNotificationName是要停止观察的消息名称
//pSender是发送者,为NULL时表示停止观察所有发送者发送的lpNotificationName所对应的消息
//当lpNotificationName为NULL时表示停止观察所有的消息
//pNotification是指定的消息中心,为默认值NULL是表示使用WNNotificationCenter::DefaultCenter()
virtual void StopObserveNotification(const char* lpNotificationName = NULL, void* pSender = NULL, WNNotificationCenter* pNotificationCenter = NULL);
//开始在指定线程观察指定发送者以及消息中心的通知(字符串)
//lpNotificationName是要停止观察的消息名称
//pThread是指定的线程,为NULL时表示在当前线程观察
//pSender是发送者,为NULL时表示停止观察所有发送者发送的lpNotificationName所对应的消息
//当lpNotificationName为NULL时表示停止观察所有的消息
//pNotification是指定的消息中心,为默认值NULL是表示使用WNNotificationCenter::DefaultCenter()
//返回值为通知Id,返回值为非0表示成功,否则表示失败
virtual unsigned int StartObserveNotificationOnThread(const char *lpNotificationName, WNWorkThread* pThread = NULL, void *pSender = NULL, WNNotificationCenter *pNotificationCenter = NULL);
//停止在指定的线程观察指定发送者以及消息中心的通知(字符串)
//lpNotificationName是要停止观察的消息名称
//pThread是指定的线程,为NULL时表示在当前线程观察
//pSender是发送者,为NULL时表示停止观察所有发送者发送的lpNotificationName所对应的消息
//当lpNotificationName为NULL时表示停止观察所有的消息
//pNotification是指定的消息中心,为默认值NULL是表示使用WNNotificationCenter::DefaultCenter()
virtual void StopObserveNotificationOnThread(const char* lpNotificationName = NULL, WNWorkThread* pThread = NULL, void* pSender = NULL, WNNotificationCenter* pNotificationCenter = NULL);
};
//WNObserverInfo用于保存观察者的信息
class WNObserverInfo
{
public:
WNObserverInfo();
virtual ~WNObserverInfo(){}
public:
WNNotificationReceiver* mpNotificationReceiver; //通知接受者
void* mpNotificationSender; //通知发送者
bool mbIsValid; //是否有效
};
//WNNotificationObserverList用于保存指定通知的观察者信息列表
class WNNotificationObserverList : public WNCLoopList<WNObserverInfo>
{
public:
WNNotificationObserverList();
virtual ~WNNotificationObserverList();
//添加观察者
void AddObserver(WNNotificationObserver* pObserver, void* pSender);
//移除观察者
void RemoveObserver(WNNotificationObserver* pObserver, void* pSender);
//投递通知
void PostNotification(WNNotification* pNotification, void* pSender = NULL);
public:
unsigned int muNotificationId; //通知Id
string mstrNotificationName; //通知名称
WNCreticalSection* mpLocker;
protected:
unsigned int muNotificationLevel; //同一线程中PostNotification函数调用的层次
unsigned int muRemoveCount; //要删除的观察者数目,用于同一线程的通知中调用RemoveObserver函数
};
//WNNotificationCenter是通知中心类
//默认会存在一个实例,通过WNNotificationCenter::DefaultCenter()获得
class WNNotificationCenter : public WNObject
{
public:
WNNotificationCenter();
virtual ~WNNotificationCenter(void);
//获得默认通知中心实例
static WNNotificationCenter* DefaultCenter();
//注册通知
//返回通知id
//如果通知未注册则返回新的id,如果已注册则返回已有id
virtual unsigned int RegisterNotification(const char* lpNotificationName);
//根据通知名称获得通知id
//如果指定的名称没有注册,则返回0,已注册返回非0的id
virtual unsigned int GetNotificationIdByName(const char* lpNotificationName);
//根据通知id得到通知名称
virtual const char* GetNotificationNameById(unsigned int uNotificationId);
//添加观察者
//pObserver是要添加的观察者
//lpNotificationName是要观察的消息名称
//pSender是指定的消息发送者,如果为NULL则观察来自所有观察者的lpNotificationName
//返回值为要观察的消息Id
virtual unsigned int AddObserver(WNNotificationObserver* pObserver, const char* lpNotificationName, void* pSender = NULL);
//移除观察者
//pObserver是要移除的观察者
//lpNotificationName是指定的通知,为NULL表示移除此观察者所有的通知,否则移除与lpNotificationName以及pSender匹配的观察者
//pSender是消息的发送者,当lpNotificationName为NULL时被忽略
// 为NULL时表示停止观察所有发送者发送的lpNotificationName所对应的消息
virtual void RemoveObserver(WNNotificationObserver* pObserver, const char* lpNotificationName = NULL, void* pSender = NULL);
//投递通知,低效方法,投递之前会先将lpNotificationName转换为Id
//lpNotificationName是通知名称
//pNotificationData是要投递的数据
//pSender是发送者
//成功返回TRUE,失败返回FALSE
virtual bool PostNotification(const char* lpNotificationName, WNObject* pNotificationData = NULL, void* pSender = NULL);
//投递通知,高效方法
//lpNotificationName是通知Id
//pNotificationData是要投递的数据
//pSender是发送者
//成功返回TRUE,失败返回FALSE
virtual bool PostNotification(unsigned int uNotificationId, WNObject* pNotificationData = NULL, void* pSender = NULL);
//投递通知,最高效方法
//pNotification是要投递的通知,投递之前设置muNotificationId以及mpNotificationData即可
//pSender是发送者
//成功返回TRUE,失败返回FALSE
//由于此方法中的pNotification参数可以使用栈上分配的对象,因此效率最高
//需要注意的是,接收者对pNotification进行Retain操作可能会由于是在栈上分配而导致不可预料的结果
//此时可以检测pNotification的mbIsAllocOnHeap成员来判断pNotification是否为栈上分配的
virtual bool PostNotification(WNNotification* pNotification, void* pSender = NULL);
protected:
WNNotificationObserverList** mppNotificationObserverList; //消息观察者列表数组
unsigned int muNotificationListMaxCount; //消息观察者列表数组最大数量
unsigned int muNextNotificationId; //下一次注册时使用的消息id
WNReadWriteLocker* mpReadWriteLocker; //读写锁
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNOBJECT_H
#define WNOBJECT_H
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
class WNObject;
class WNCreticalSection;
class WNObjectDelegate;
template <class T> class WNSmartPtr;
class WNObjectTypeFnBase
{
public:
virtual ~WNObjectTypeFnBase() { }
virtual void DoDestroy(void* pDes) const { }
};
template <typename T>
class WNObjectTypeFn : public WNObjectTypeFnBase
{
public:
virtual ~WNObjectTypeFn() { }
T* DoConvert(void* pDes) const
{
return (T*)(pDes);
}
virtual void DoDestroy(void* pDes) const
{
delete DoConvert(pDes);
}
};
template <typename T>
static WNObjectTypeFn<T>* getWNObjectTypeFnInstance()
{
static WNObjectTypeFn<T> mInstance;
return &mInstance;
}
//只能以指针形式使用
class WNObject
{
public:
WNObject();
virtual ~WNObject();
//初始化计数器
virtual void ResetRefInfo();
//初始化计数器以及设置托管对象
virtual void ResetRefInfoAndDelegate(WNObjectDelegate* pDelegate = NULL);
//设置对象的安全锁
//为空时表示创建安全锁
//否则使用传入的安全锁
virtual void SetSafeLocker(WNCreticalSection* pLocker = NULL);
//获得对象的安全锁
WNCreticalSection* GetSafeLocker();
//取消安全锁
virtual void ResetSafeLocker();
//增加对象的引用
//返回对象的this指针
virtual WNObject* Retain();
//减少对象的引用
//bClearDelayRelease表示是否清空延迟减少计数器
//返回对象的this指针,如果对象已销毁则返回NULL
virtual WNObject* Release(bool bClearDelayRelease = true);
//自动释放
virtual WNSmartPtr<WNObject*> AutoRelease();
//延迟减少对象的引用(增加延迟减少计数器)
//返回对象的this指针
virtual WNObject* DelayRelease();
//处理延迟减少计数器
//如果bOnlySetZero为TRUE,则仅仅将延迟引用计数器置零,
//默认会做如下操作:
//miRetainCount -= miDelayReleaseCount
//如果当前对象引用为0,则会调用delete操作
virtual WNObject* ClearDelayRelease(bool bOlnySetZero = false);
//当前的引用计数器的值
inline int RetainCount() { return miRetainCount; }
//当前延迟引用计数器的值
inline int DelayCount() { return miDelayReleaseCount; }
//当前实际的引用计数器
inline int RefCount() { return miRetainCount - miDelayReleaseCount; }
//设置或者或其托管对象
inline WNObjectDelegate*& Delegate() { return mpDelegate; }
public:
int miRetainCount : 31; //引用计数器
bool mbIsAllocOnHeap : 1; //是否在堆上分配
int miDelayReleaseCount; //延迟减少计数器
WNObjectDelegate* mpDelegate; //托管对象
WNCreticalSection* mpLoker; //安全锁
bool mbIsOwnLocker; //安全锁是否属于自己
void* mpThis; //当前对象new出来的指针
WNObjectTypeFnBase* mpTypeFn; //用于析构mpThis的对象
};
typedef WNObject* obj;
//WNObject*类型的智能指针,T只允许为指针类型
template <class T>
class WNSmartPtr
{
public:
T ptr;
public:
inline WNSmartPtr() { ptr = 0; }
inline WNSmartPtr(const WNSmartPtr<T>& sPtr):ptr(0) { *this = sPtr; }
inline WNSmartPtr(const T& pPtr):ptr(0) { *this = (obj&)pPtr; }
virtual ~WNSmartPtr(){}
template <typename Ptr>
inline WNSmartPtr(const Ptr pPtr):ptr(0) { *this = (obj&)pPtr; }
virtual bool isEqualTo(const obj& pPtr) const
{
return pPtr == (obj)ptr;
}
template <typename Ptr>
inline bool operator == (const Ptr& pPtr) const
{
return isEqualTo((obj&)pPtr);
}
inline bool operator == (const WNSmartPtr<T>& sPtr) const
{
return *this == (obj&)(sPtr.ptr);
}
template <typename Ptr>
inline bool operator != (const Ptr& pPtr) const
{
return (*this == (obj)pPtr)?false:true;
}
inline bool operator != (const WNSmartPtr<T>& sPtr) const
{
return *this != sPtr.ptr;
}
WNSmartPtr<T>& operator = (const obj& pPtr)
{
pPtr->Retain();
if (ptr)
{
pPtr->Release();
ptr = NULL;
}
ptr = (T&)pPtr;
return *this;
}
template <typename Ptr>
inline WNSmartPtr<T>& operator = (const Ptr& pPtr) { return *this = (obj&)pPtr; }
inline WNSmartPtr<T>& operator = (const WNSmartPtr<T>& sPtr) { return *this = (obj&)(sPtr.ptr); }
template <typename ToType>
inline operator ToType& () const { return (ToType&)ptr; }
template <typename ToType>
inline operator ToType () { return (ToType)ptr; }
inline operator obj& () const { return (obj&)(ptr); }
inline operator obj () { return (obj)(ptr); }
inline T& ref() { return (T&)ptr; }
};
class WNObjectDelegate
{
public:
//当WNObject的muRetainCount以及muDelayReleaseCount的差变为0时触发
//如果返回值为TRUE则会delete此对象
virtual bool OnWNObjectRetainCountIsZero(WNObject* pObject) { return true; }
virtual ~WNObjectDelegate(){}
};
//只能以指针形式使用
template <class T>
class WNObjectEx : public WNObject
{
public:
T dataRef;
};
template <typename WNObjectClass>
WNObjectClass* _WNAlloc()
{
WNObjectClass* pObject = new WNObjectClass;
pObject->mbIsAllocOnHeap = true;
pObject->mpThis = pObject;
pObject->mpTypeFn = getWNObjectTypeFnInstance<WNObjectClass>();
return pObject;
}
template <typename WNObjectClass>
WNObjectClass* _WNSafeAlloc()
{
WNObjectClass* pObject = new WNObjectClass;
pObject->SetSafeLocker();
pObject->mbIsAllocOnHeap = true;
pObject->mpThis = pObject;
pObject->mpTypeFn = getWNObjectTypeFnInstance<WNObjectClass>();
return pObject;
}
#ifndef WNAlloc
#define WNAlloc(WNObjectClass) _WNAlloc<WNObjectClass>()
#endif
#ifndef WNSafeAlloc
#define WNSafeAlloc(WNObjectClass) _WNSafeAlloc<WNObjectClass>()
#endif
//#define doRelease(ppObj) _doRelease((WNObject**)(&(ppObj)))
//void _doRelease(WNObject** ppObj);
//#define doAutoRelease(ppObj) _doDelayRelease((WNObject**)(&(ppObj)))
//void _doDelayRelease(WNObject** ppObj);
#define doRelease(pObj) \
if (pObj) \
{ \
pObj->Release(); \
pObj = 0; \
}
#define doDelayRelease(pObj) \
if (pObj) \
{ \
pObj->DelayRelease(); \
pObj = 0; \
}
//template <typename T>
//void doRelease(T*& pObjRef)
//{
// pObjRef->Release();
// pObjRef = NULL;
//}
//
//template <typename T>
//void doDelayRelease(T*& pObjRef)
//{
// pObjRef->DelayRelease();
// pObjRef = NULL;
//}
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNREADWRITELOCKER_H
#define WNREADWRITELOCKER_H
class WNCreticalSection;
class WNReadWriteLocker
{
public:
WNReadWriteLocker();
virtual ~WNReadWriteLocker();
bool LockRead(unsigned long dwTimeOut = 0);
bool LockWrite(unsigned long dwTimeOut = 0);
bool ReleaseRead();
bool ReleaseWrite();
protected:
bool InternalLockRead();
bool InternalLockWrite();
private:
unsigned long m_dwReadCount;
unsigned long m_dwWriteCount;
bool m_bWriting;
WNCreticalSection* mpLocker;
};
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNSOCKETOBSERVER_H
#define WNSOCKETOBSERVER_H
#include "WNCLoopList.h"
#include "WNCreticalSection.h"
#include <string>
using namespace std;
class WNSocketObserverTarget;
#ifndef INVALID_SOCKET
#define INVALID_SOCKET -1
#endif
#ifndef SD_BOTH
#define SD_BOTH 2
#endif
#ifndef SOCKET_ERROR
#define SOCKET_ERROR (-1)
#endif
class IWNSocketObserver
{
public:
virtual bool AddSocket(WNSocketObserverTarget* socketInfo) = 0;
virtual bool RemoveSocket(WNSocketObserverTarget* socketInfo) = 0;
virtual bool StartServer() = 0;
virtual bool StopServer() = 0;
virtual const char* GetServerName() = 0;
virtual ~IWNSocketObserver(){}
virtual bool IsWorking() = 0;
};
typedef WNCLoopList<IWNSocketObserver*> WNSocketObserverList;
class WNSocketObserverTargetDelegate
{
public:
//当前socket可读(或可以进行accept操作)
virtual void OnObserverRead(IWNSocketObserver* observer) = 0;
//当前socket错误
virtual void OnObserverError(IWNSocketObserver* observer) = 0;
virtual ~WNSocketObserverTargetDelegate(){}
};
class WNSocketObserverTarget
{
public:
WNSocketObserverTarget();
virtual ~WNSocketObserverTarget();
enum ObserverState
{
None, //不在观察者server中
Adding, //正在添加至观察者列表
Observering, //正在观察
Removing //正在从观察者列表中移除
};
enum SocketState
{
SS_None, //无状态,无有效socket
SS_Normal, //正常状态,可以读写
SS_Listening, //侦听状态
SS_Accepting, //等待accept
SS_Connecting, //连接状态
SS_Reading, //读状态
SS_Writing, //写状态
SS_Closing //正在关闭
};
virtual void CreateLocker();
virtual void DestroyLocker();
virtual bool TryLock();
virtual bool Lock();
virtual bool Unlock();
public:
int mSocket;
volatile SocketState mSocketState;
string mObserverName;
//CRITICAL_SECTION* mpLocker;
WNCreticalSection* mpLocker;
unsigned long mlLockRef;
unsigned long mdwLockedThreadId;
WNSocketObserverTargetDelegate* mpObserverTargetDelegate;
int miObserverErrorCode;
pthread_t mLockedThreadId;
};
typedef WNCLoopList<WNSocketObserverTarget*> WNSocketObserverTargetList;
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNSOCKETOBSERVERMANAGER_H
#define WNSOCKETOBSERVERMANAGER_H
#include "WNSocketObserver.h"
class WNSocketObserverManager
{
public:
WNSocketObserverManager();
public:
static bool RegisterObserver(IWNSocketObserver* observer);
static IWNSocketObserver* GetObserverByName(const char* lpName);
static WNSocketObserverList* GetObserverList();
static bool AddSocket(WNSocketObserverTarget* socketInfo);
static bool RemoveSocket(WNSocketObserverTarget* socketInfo);
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNSOCKETSELECTOBSERVER_H
#define WNSOCKETSELECTOBSERVER_H
#include "WNSocketObserver.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <pthread.h>
class WNSocketSelectObserver : IWNSocketObserver
{
public:
WNSocketSelectObserver();
~WNSocketSelectObserver();
virtual bool AddSocket(WNSocketObserverTarget* socketInfo);
virtual bool RemoveSocket(WNSocketObserverTarget* socketInfo);
virtual bool StartServer();
virtual bool StopServer();
virtual const char* GetServerName();
virtual bool IsWorking();
protected:
static void* SelectThreadProc(void* lpParameter);
virtual bool InternalStartServer();
virtual bool InternalStopServer();
virtual bool InternalAddSocket(WNSocketObserverTarget* socketInfo);
virtual bool InternalRemoveSocket(WNSocketObserverTarget* socketInfo);
virtual long InternalSelectThreadProc();
virtual void CreateLocker();
virtual void DestroyLocker();
virtual bool TryLock();
virtual bool Lock();
virtual bool Unlock();
protected:
pthread_t mdwThreadId; //select线程id
int mThreadHandle; //select线程handle
bool mbIsWorking; //表示工作线程正在工作
bool mbExitThread; //是否需要退出线程
WNSocketObserverTargetList mTargetList; //目标socket列表
WNCreticalSection* mpOperateLocker; //操作锁
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNTIMER_H
#define WNTIMER_H
#include "ACCallback.h"
class WNTimer;
typedef void (*TimerProc)(long hwnd, unsigned int uMsg, unsigned int* idEvent, unsigned long dwTime);
typedef void (*WNTimerDelegate)(WNTimer* pTimer, unsigned int uFireTimes);
class WNTimer : public ACCallbackEx<WNTimerDelegate>
{
public:
WNTimer();
~WNTimer();
//开始计时器
//uInterval表示触发间隔
//如果计时器已经存在,则重置计时器
void StartTimer(unsigned int uInterval);
//停止计时器
void StopTimer();
//触发计时器(调用一次托管函数)
void Fire();
protected:
void InternalTimerProc(int i);
public:
unsigned int* muTimerId;
unsigned int muFireTimes;
unsigned int muInterval;
ACCallbackEx<TimerProc> mTimerProc;
};
#endif
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef WNWORKTHREAD_H
#define WNWORKTHREAD_H
//#include "WNInvoker.h"
#include "WNCreticalSection.h"
#include "WNNotificationCenter.h"
#include "WNCLoopList.h"
#include <pthread.h>
class WNWorkThread;
class WNNotification;
class WNNotificationObserver;
class WNNotificationCenter;
#define WN_WORK_THREAD_EXIT false
#define WN_WORK_THREAD_CONTINUE true
typedef pthread_t WNThreadId;
enum ThreadResetFlag
{
TRF_ResetMember, //重置成员信息
TRF_DeleteInstance //delete实例
};
class WNWorkThreadDelegate
{
public:
virtual bool OnWorkThreadStart(WNWorkThread* objThread) { return WN_WORK_THREAD_CONTINUE; }
virtual bool OnWorkThreadProc(WNWorkThread* objThread, unsigned int& uStep) { return WN_WORK_THREAD_EXIT; }
virtual unsigned int OnWorkThreadProcEnd(WNWorkThread* objThread) { return 0; }
virtual unsigned int OnWorkThreadNeedSleep(WNWorkThread* objThread) { return 1; }
virtual ~WNWorkThreadDelegate(){}
};
class WNThreadObserverInfoItem
{
public:
WNThreadObserverInfoItem();
WNNotificationObserver* mpObserver;
void* mpSender;
};
typedef WNCLoopList<WNThreadObserverInfoItem> WNThreadObserverInfoItemList;
class WNThreadObserverInfo
{
public:
WNThreadObserverInfo();
unsigned int muNotificationId;
WNNotificationCenter* mpCenter;
WNThreadObserverInfoItemList mObserverList;
};
typedef WNCLoopList<WNThreadObserverInfo> WNThreadObserverInfoList;
class WNWorkThread : public WNNotificationObserver//, public WNInvoker
{
public:
typedef void (*WNThreadDestroyFn)(WNWorkThread* pThread);
public:
WNWorkThread(void);
virtual ~WNWorkThread(void);
static unsigned int GetTickCount();
//线程睡眠,默认单位是毫秒
//最终的睡眠时间是uTimeOut * uMultiplier,单位是微妙
static void Sleep(unsigned int uTimeout, unsigned uMultiplier = 1000);
static void DoEvents(WNWorkThread* pThread = NULL);
static void DoEvents(unsigned int uTimeOut, WNWorkThread* pThread = NULL);
static void DoEventsAndSleep(unsigned int uSleepTime, WNWorkThread* pThread = NULL);
static void DoEventsAndSleep(unsigned int uTimeOut, unsigned int uSleepTime, WNWorkThread* pThread = NULL);
static WNWorkThread* GetCurrentThread();
static WNWorkThread* GetMainThread();
//外部线程调用,结束指定线程
//linux下无法使用
static bool DoTerminateThread(WNThreadId threadId, unsigned int uExitCode = 0 );
//内部线程调用,结束当前函数执行线程
//不建议直接调用,建议使用EndWork()结束线程
static void DoExitThread(unsigned int uExitCode = 0);
virtual void StartWork();
//结束线程
//dwTimeOut表示正常结束后超出多长时间后强制结束线程
//linux下强制结束线程尚未实现
virtual void EndWork(unsigned int dwTimeOut = 500);
//返回是否为主线程
virtual bool IsMainThread();
//返回线程是否正在运行
virtual bool IsThreadRunning();
//返回是否为当前线程
virtual bool IsCurrentThread();
inline WNWorkThreadDelegate*& Delegate() { return mpThreadDelegate; }
inline WNThreadId ThreadId() { return mThreadId; }
inline ThreadResetFlag& ResetFlag( ) { return mResetFlag; }
inline WNThreadDestroyFn ThreadDestroyFn() { return mpThreadDestroyFn; }
//在当前线程添加观察者,指定发送者以及消息中心的通知(字符串),当前线程作为消息中转站
//只有当线程在工作的时候才会有效
//pObserver是观察者
//lpNotificationName是要观察的通知名称
//pSender是发送者,为NULL时表示观察所有发送者发送的lpNotificationName
//pNotification是指定的消息中心,为默认值NULL是表示使用WNNotificationCenter::DefaultCenter()
//返回值为通知Id,返回值为非0表示成功,否则表示失败
virtual unsigned int AddObserve4Notification(WNNotificationObserver* pObserver, const char* lpNotificationName, void* pSender = NULL, WNNotificationCenter* pNotificationCenter = NULL);
//在当前线程移除观察者,指定发送者以及消息中心的通知(字符串),当前线程作为消息中转站
//只有当线程在工作的时候才会有效
//pObserver是观察者
//lpNotificationName是要停止观察的消息名称
//pSender是发送者,为NULL时表示停止观察所有发送者发送的lpNotificationName所对应的消息
//当lpNotificationName为NULL时表示停止观察所有的消息
//pNotification是指定的消息中心,为默认值NULL是表示使用WNNotificationCenter::DefaultCenter()
virtual void RemoveObserve4Notification(WNNotificationObserver* pObserver, const char* lpNotificationName = NULL, void* pSender = NULL, WNNotificationCenter* pNotificationCenter = NULL);
//向当前线程投递消息
virtual bool PostThreadMessage(WNNotification *pNotification);
//处理队列中的线程消息
//返回false表示线程队列中无消息
//返回true表示处理了一个线程消息
virtual bool ProcessMessageInQueue();
//清空线程消息队列
virtual void ClearMessageQueue();
protected:
virtual void OnReceiveNotification(WNNotification* pNotification);
protected:
static void* InternalThreadMain( void* lpParam );
//创建线程
//成功返回true,失败返回false
virtual bool CreateThread();
virtual unsigned int ThreadMain();
virtual bool ThreadProc(unsigned int uStep);
//重置为初始状态(StartWork之前的状态)
//mpThreadDelegate不会重置
virtual void DoReset();
//等待线程结束,在外部线程使用
//dwTimeOut表示超时
//如果在dwTimeOut之内正常结束,则返回true,否则返回false
virtual bool WaitThreadEnd(unsigned int dwTimeOut = 500);
protected:
WNWorkThreadDelegate* mpThreadDelegate;
volatile bool mbExitOutThread; //线程外退出标志
volatile bool mbExitInThread; //线程内退出标志
WNThreadId mThreadId;
void* mThreadHandle;
unsigned int muLastThreadExitCode; //最后一次线程退出代码
volatile bool mbIsThreadRunning; //线程是否正在运行
ThreadResetFlag mResetFlag; //线程重置标志位,线程退出时有效,TRF_DeleteInstance只能在线程自己结束的情况下使用
WNThreadDestroyFn mpThreadDestroyFn; //线程销毁函数
WNCLoopList<WNNotification*> mMsgQueue; //消息处理队列
WNCreticalSection mMsgQueueLocker; //消息处理队列锁
WNThreadObserverInfoList mObserverInfoList; //消息转发映射表
WNCreticalSection mObserverListLocker; //消息转发映射表锁
};
#endif
/*utf8解析行 Don't remove or modify this first line!*/
#ifndef CFG_INI_FILE_H_
#define CFG_INI_FILE_H_
#ifdef __cplusplus
extern "C"
{
#endif
int read_profile_string( char *section, char *key,char *value, int size,char *default_value, const char *file);
int read_profile_int( char *section, char *key,int default_value, const char *file);
int write_profile_string( char *section, char *key, char *value, const char *file);
#ifdef __cplusplus
};
#endif
#endif
# Copyright (C) 2011 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
CFLAGS += -g
CXXFLAGS += -fPIE
#include $(ANDROID_BUILD_TOP)/external/stlport/stlport.mk
include $(ANDROID_BUILD_TOP)/external/stlport/libstlport.mk
LOCAL_MODULE := libWaninCommon
LOCAL_C_INCLUDES += \
$(ANDROID_BUILD_TOP)/wanin/CommonLibraries/include
LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)
LOCAL_SRC_FILES := WNObject.cpp WNCStringList.cpp IniFileManager.cpp WNWorkThread.cpp WNSocketObserverManager.cpp WNSocketSelectObserver.cpp WNSocketObserver.cpp WNCommonSocket.cpp WNNotificationCenter.cpp WNByteBufferManager.cpp WNByteBuffer.cpp WNReadWriteLocker.cpp MD5Checksum.cpp WNCreticalSection.cpp WNBitIndex.cpp
LOCAL_SHARED_LIBRARIES := liblog libstlport
LOCAL_MODULE_TAGS := optional
include $(BUILD_SHARED_LIBRARY)
# Copyright (C) 2011 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := libWaninCommon
LOCAL_C_INCLUDES += \
$(LOCAL_PATH)/../include/
LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)
LOCAL_SRC_FILES := WNObject.cpp WNCStringList.cpp IniFileManager.cpp WNSocketObserverManager.cpp WNSocketSelectObserver.cpp WNSocketObserver.cpp WNCommonSocket.cpp WNNotificationCenter.cpp WNByteBufferManager.cpp WNByteBuffer.cpp WNReadWriteLocker.cpp MD5Checksum.cpp WNCreticalSection.cpp WNBitIndex.cpp
LOCAL_SHARED_LIBRARIES := liblog libstlport
LOCAL_MODULE_TAGS := optional
include $(BUILD_SHARED_LIBRARY)
APP_CFLAGS += -fexceptions
APP_STL := stlport_static
This source diff could not be displayed because it is too large. You can view the blob instead.
/*utf8解析行 Don't remove or modify this first line!*/
//nclude "stdafx.h"
#include "WNByteBuffer.h"
#include <memory.h>
ByteBuffer::ByteBuffer(unsigned long dwBufferSize /* = DEFAULT_BUFFER_SIZE */)
:m_dwFlag(0)
,m_pBuffer(NULL)
,m_dwBufferSize(0)
,m_dwValidSize(0)
,m_pPos(NULL)
{
if (dwBufferSize)
{
InitBuffer(dwBufferSize);
}
}
ByteBuffer::ByteBuffer( ByteBuffer& srcByteBuffer )
:m_pBuffer(NULL)
,m_dwBufferSize(0)
,m_dwValidSize(0)
,m_pPos(NULL)
{
*this = srcByteBuffer;
}
ByteBuffer::ByteBuffer( void* pData, unsigned long dwSize )
:m_pBuffer(NULL)
,m_dwBufferSize(0)
,m_dwValidSize(0)
,m_pPos(NULL)
{
ReadMemory(pData, dwSize);
}
ByteBuffer::~ByteBuffer()
{
ReleaseBuffer();
}
bool ByteBuffer::InitBuffer(unsigned long dwBufferSize /* = DEFAULT_BUFFER_SIZE */, bool bReserveData /* = false */, bool bReservePos /* = false */)
{
WNByteBuffer newBuffer(0);
if (!dwBufferSize)
{
ReleaseBuffer();
return true;
}
if (dwBufferSize)
{
newBuffer.m_pBuffer = new unsigned char[dwBufferSize + 2];
memset(newBuffer.m_pBuffer, 0, dwBufferSize + 2);
newBuffer.m_dwFlag = m_dwFlag;
newBuffer.m_dwBufferSize = dwBufferSize;
newBuffer.m_dwValidSize = dwBufferSize;
newBuffer.m_pPos = newBuffer.m_pBuffer;
}
if (bReserveData && m_pBuffer)
{
memcpy(newBuffer.m_pBuffer, m_pBuffer, (dwBufferSize > m_dwBufferSize)?m_dwBufferSize:dwBufferSize);
}
if (bReservePos)
{
newBuffer.SetPos(GetPos());
newBuffer.SetValidSize(GetValidSize());
}
ReleaseBuffer();
m_dwFlag = newBuffer.m_dwFlag;
m_pBuffer = newBuffer.m_pBuffer;
m_dwBufferSize = newBuffer.m_dwBufferSize;
m_dwValidSize = newBuffer.m_dwValidSize;
m_pPos = newBuffer.m_pPos;
newBuffer.m_pBuffer = NULL;
return true;
}
bool ByteBuffer::ReleaseBuffer()
{
if (m_pBuffer)
{
delete[] m_pBuffer;
m_pBuffer = NULL;
m_pPos = NULL;
m_dwBufferSize = 0;
m_dwValidSize = 0;
}
return true;
}
//bool ByteBuffer::ReadFile(FILE* pFile, unsigned long dwReadSize /* = 0 */)
//{
// if (!pFile)
// {
// return FALSE;
// }
// if (!dwReadSize)
// {
// if (m_pBuffer)
// {
// dwReadSize = m_dwBufferSize;
// }
// else
// {
// InitBuffer(dwReadSize);
// }
// }
// else if (dwReadSize != m_dwBufferSize)
// {
// InitBuffer(dwReadSize);
// }
//
// unsigned long dwReadCount = fread(m_pBuffer, dwReadSize, 1, pFile);
//#ifndef MAC_PROGRAME
// return (dwReadCount == dwReadSize)?true:FALSE;
//#else
// return (dwReadCount == 1)?true:FALSE;
//#endif
//}
bool ByteBuffer::ReadMemory(const void* pSrcData, unsigned long dwReadSize /* = 0 */)
{
if (!pSrcData)
{
return false;
}
if (!dwReadSize)
{
if (m_pBuffer)
{
dwReadSize = m_dwBufferSize;
}
else
{
InitBuffer(dwReadSize);
}
}
else if (dwReadSize != m_dwBufferSize)
{
InitBuffer(dwReadSize);
}
memcpy(m_pBuffer, pSrcData, dwReadSize);
return true;
}
unsigned long ByteBuffer::OutputWithPos(void* pTarData, unsigned long dwOutputSize /* = 0 */, const unsigned long* pdwPos /* = NULL */)
{
if (!(m_pBuffer && m_dwBufferSize))
{
return 0;
}
if (!pTarData)
{
return 0;
}
if (!dwOutputSize)
{
dwOutputSize = m_dwBufferSize;
}
if (pdwPos)
{
m_pPos = m_pBuffer + *pdwPos;
}
if (m_pPos >= m_pBuffer + m_dwBufferSize)
{
return 0;
}
else if (m_pPos + dwOutputSize < m_pBuffer + m_dwBufferSize)
{
memcpy(pTarData, m_pPos, dwOutputSize);
m_pPos += dwOutputSize;
return dwOutputSize;
}
else
{
dwOutputSize = m_pBuffer + m_dwBufferSize - m_pPos;
memcpy(pTarData, m_pPos, dwOutputSize);
m_pPos += dwOutputSize;
return dwOutputSize;
}
}
unsigned long ByteBuffer::InputWithPos(const void* pSrcData, unsigned long dwInputSize /*= 0*/, const unsigned long* pdwPos /*= NULL */ )
{
if (!(m_pBuffer && m_dwBufferSize))
{
return 0;
}
if (!pSrcData)
{
return 0;
}
if (!dwInputSize)
{
return 0;
}
if (pdwPos)
{
m_pPos = m_pBuffer + *pdwPos;
}
if (m_pPos >= m_pBuffer + m_dwBufferSize)
{
return 0;
}
else if (m_pPos + dwInputSize > m_pBuffer + m_dwBufferSize)
{
unsigned char* pOldPos = m_pPos;
InitBuffer(m_dwBufferSize + dwInputSize, true);
m_pPos = pOldPos;
memcpy(m_pPos, pSrcData, dwInputSize);
m_pPos += dwInputSize;
return dwInputSize;
}
else
{
memcpy(m_pPos, pSrcData, dwInputSize);
m_pPos = m_pPos + dwInputSize;
return dwInputSize;
}
}
ByteBuffer& ByteBuffer::operator = ( const ByteBuffer& SrcByteBuffer )
{
if (!SrcByteBuffer.m_pBuffer)
{
ReleaseBuffer();
}
else
{
InitBuffer(SrcByteBuffer.m_dwBufferSize);
memcpy(m_pBuffer, SrcByteBuffer.m_pBuffer, m_dwBufferSize);
}
return *this;
}
ByteBuffer& ByteBuffer::operator=( const char* strData )
{
unsigned long dwSize = strlen(strData);
InitBuffer(dwSize);
memcpy(m_pBuffer, strData, dwSize);
return *this;
}
bool ByteBuffer::operator==( const ByteBuffer& srcData )
{
if (&srcData == this)
{
return true;
}
else if (m_dwBufferSize == srcData.m_dwBufferSize)
{
if (m_pBuffer && srcData.m_pBuffer)
{
for (unsigned long i = 0; i < m_dwBufferSize; i++)
{
if (m_pBuffer[i] != srcData.m_pBuffer[i])
{
return false;
}
}
return true;
}
else if (!m_pBuffer && !srcData.m_pBuffer)
{
return true;
}
}
return false;
}
bool ByteBuffer::operator==( const char* strSrc )
{
if (!strSrc)
{
return false;
}
if (m_pBuffer)
{
if (!strcmp((char*)m_pBuffer, strSrc))
{
return true;
}
}
else if (!strSrc)
{
return true;
}
return false;
}
//bool ByteBuffer::SaveFile(const char* strFilename, bool bUseValidSize /* = true */)
//{
// FILE* pFile = fopen(strFilename, "wb");
// if (!pFile)
// {
// return FALSE;
// }
// fwrite(m_pBuffer, bUseValidSize?m_dwValidSize:m_dwBufferSize, 1, pFile);
// fclose(pFile);
// return true;
//}
unsigned long ByteBuffer::SetValidString( unsigned long dwStrLen )
{
if (dwStrLen < m_dwBufferSize)
{
memset(m_pBuffer + dwStrLen, m_dwBufferSize - dwStrLen, 0);
m_dwValidSize = dwStrLen;
}
return m_dwValidSize;
}
unsigned long ByteBuffer::SetValidSize( unsigned long dwSize )
{
if (dwSize < m_dwBufferSize)
{
m_dwValidSize = dwSize;
}
else
{
m_dwValidSize = m_dwBufferSize;
}
return m_dwValidSize;
}
WNByteBuffer::WNByteBuffer( unsigned long dwBufferSize /*= DEFAULT_BUFFER_SIZE*/ )
:ByteBuffer(dwBufferSize)
,mpBufferManager(NULL)
{
}
/*utf8解析行 Don't remove or modify this first line!*/
#ifdef __WINOS__
#include "StdAfx.h"
#endif
#define DEFAULT_BUFFER_SIZE 0
#include "WNByteBufferManager.h"
WNByteBufferList::WNByteBufferList()
:muBufferSize(0)
{
}
WNByteBufferManager::WNByteBufferManager(unsigned int uMinBufferSize /* = DefMinBufferSize */, unsigned int uSetpBufferSize /* = DefSetpBufferSize */, unsigned int uMaxBufferSize /* = DefMaxBufferSize */)
:mpBufferList(NULL)
,muListCount(0)
,muMinBufferSize(0)
,muStepBufferSize(0)
,muMaxBufferSize(0)
,muAllBufferSize(0)
,muMaxAllBufferSize(DefMaxAllBufferSize)
,muAllBufferCount(0)
,muMaxAllBufferCount(DefMaxBufferCount)
{
InitManager(uMinBufferSize, uSetpBufferSize, uMaxBufferSize);
}
WNByteBufferManager::~WNByteBufferManager(void)
{
FreeManager();
}
//进1取整宏
#define INTV(x, y) ((x + y - 1) / y)
void WNByteBufferManager::InitManager( unsigned int uMinBufferSize, unsigned int uStepBufferSize, unsigned int uMaxBufferSize )
{
if (!uStepBufferSize)
{
uStepBufferSize = DefSetpBufferSize;
}
if (uMaxBufferSize < uMinBufferSize)
{
uMaxBufferSize = uMinBufferSize;
}
if (muListCount)
{
if (uMaxBufferSize != muMaxBufferSize)
{
FreeManager();
}
else if (uStepBufferSize != muStepBufferSize)
{
FreeManager();
}
else if (INTV((uMaxBufferSize - uMinBufferSize), uStepBufferSize) != INTV((muMaxBufferSize - muMinBufferSize), muStepBufferSize))
{
FreeManager();
}
else
{
//所有参数相同,无需重新初始化
return;
}
}
muMinBufferSize = uMinBufferSize;
muStepBufferSize= uStepBufferSize;
muMaxBufferSize = uMaxBufferSize;
muListCount = INTV((muMaxBufferSize - muMinBufferSize), muStepBufferSize) + 1;
//初始化自由缓冲区列表数组
mpBufferList = new WNByteBufferList[muListCount + 1];
for (unsigned int i = 1; i <= muListCount; i++)
{
mpBufferList[i].muBufferSize = muMinBufferSize + muStepBufferSize * (i - 1);
}
}
void WNByteBufferManager::FreeManager()
{
if (!muListCount)
{
return;
}
delete [] mpBufferList;
mpBufferList = NULL;
muListCount = 0;
muMinBufferSize = 0;
muStepBufferSize = 0;
muMaxBufferSize = 0;
muAllBufferSize = 0;
muAllBufferCount = 0;
}
void WNByteBufferManager::InitBuffers( unsigned int uBufferSize, unsigned int uCount /*= 1*/ )
{
if (!muListCount)
{
return;
}
WNByteBufferList* pBufferList = GetListByBufferSize(uBufferSize);
for (unsigned int i = 0; i < uCount; i++)
{
WNByteBufferList::PNode pNode = new WNByteBufferList::Node;
pNode->data.InitBuffer(pBufferList->muBufferSize);
muAllBufferSize += pBufferList->muBufferSize?pBufferList->muBufferSize:uBufferSize;
muAllBufferCount++;
pBufferList->AppendNode(pNode);
}
}
WNByteBuffer* WNByteBufferManager::GetBuffer(unsigned int uBufferSize, bool mbThreadSafeBuffer /* = FALSE */)
{
if (!muListCount)
{
return NULL;
}
WNByteBufferList::PNode pNode = NULL;
Lock();
WNByteBufferList* pBufferList = GetListByBufferSize(uBufferSize);
if (pBufferList->ListCount())
{
pNode = pBufferList->DetachNode(pBufferList->Begin());
muAllBufferSize -= pNode->data.BufferSize();
muAllBufferCount--;
pNode->data.MovePosBegin();
Unlock();
}
else
{
if (pBufferList->muBufferSize)
{
//如果缓冲区列表指定的缓冲区大小不为0,则表示在范围内
uBufferSize = pBufferList->muBufferSize;
}
//Unlock();
pNode = new WNByteBufferList::Node;
if (!pNode)
{
return NULL;
}
pNode->data.mbIsAllocOnHeap = true;
if (!pNode->data.InitBuffer(uBufferSize))
{
delete pNode;
return NULL;
}
if (mbThreadSafeBuffer)
{
pNode->data.SetSafeLocker();
}
pNode->data.mpThis = pNode;
pNode->data.mpTypeFn = getWNObjectTypeFnInstance<WNByteBufferList::Node>();
pNode->data.mpBufferManager = this;
pNode->data.Delegate() = this;
pNode->data.Retain();
Unlock();
}
pNode->data.DelayRelease();
return (WNByteBuffer*)(&(pNode->data));
//return (WNByteBuffer*)(pNode->data.DelayRelease());
}
void WNByteBufferManager::FreeBuffer( WNByteBuffer* pBuffer )
{
if (!muListCount)
{
return;
}
Lock();
if ((muAllBufferCount >= muMaxAllBufferCount) || (muAllBufferSize >= muMaxAllBufferSize))
{
WNByteBufferList::PNode pNode = (WNByteBufferList::PNode)pBuffer;
delete pNode;
}
else
{
WNByteBufferList* pBufferList = GetListByBufferSize(pBuffer->BufferSize());
pBufferList->AppendNode((WNByteBufferList::PNode)pBuffer);
pBuffer->ResetRefInfo();
muAllBufferCount++;
muAllBufferSize += pBuffer->BufferSize();
}
Unlock();
}
void WNByteBufferManager::SetMaxAllBufferSize( unsigned int uSize )
{
muMaxAllBufferSize = uSize;
return;
}
void WNByteBufferManager::SetMaxBufferCount( unsigned int uCount )
{
muMaxAllBufferCount = uCount;
return;
}
WNByteBufferList* WNByteBufferManager::GetListByBufferSize( unsigned int uBufferSize )
{
if (uBufferSize < muMinBufferSize)
{
uBufferSize = muMinBufferSize;
}
if (uBufferSize > mpBufferList[muListCount].muBufferSize)
{
return mpBufferList;
}
else
{
return mpBufferList + INTV((uBufferSize - muMinBufferSize), muStepBufferSize) + 1;
}
}
bool WNByteBufferManager::OnWNObjectRetainCountIsZero( WNObject* pObject )
{
if (!muListCount)
{
return true;
}
Lock();
if ((muAllBufferCount >= muMaxAllBufferCount) || (muAllBufferSize >= muMaxAllBufferSize))
{
Unlock();
return true;
}
else
{
WNByteBufferList::PNode pNode = NULL;
pNode = (WNByteBufferList::PNode)(pObject->mpThis);
WNByteBufferList* pBufferList = GetListByBufferSize(pNode->data.BufferSize());
pBufferList->AppendNode(pNode);
pNode->data.ResetRefInfo();
muAllBufferCount++;
muAllBufferSize += pNode->data.BufferSize();
Unlock();
return false;
}
}
/*utf8解析行 Don't remove or modify this first line!*/
#ifdef __WINOS__
#include "stdafx.h"
#endif
#include "WNCStringList.h"
WNCStringList::WNCStringList(const char* lpStringList, const char* lpSplit /* = _T("|") */)
{
CreateList(lpStringList, lpSplit);
}
WNCStringList::WNCStringList(const string& strStringList, const string& strSplit /* = _T("|") */)
{
CreateList(strStringList, strSplit);
}
void WNCStringList::CreateList(const char* lpStringList /* = _T("") */, const char* lpSplit /* = _T("|") */)
{
if (!lpStringList)
{
return;
}
string strList(lpStringList);
string strSplit(lpSplit);
if (strSplit == "")
{
string strToken;
while (*lpStringList)
{
PNode node = new Node;
node->data = lpStringList;
AppendNode(node);
lpStringList += node->data.length();
lpStringList++;
}
}
else
{
return CreateList(strList, strSplit);
}
}
void WNCStringList::CreateList(const string& strStringList, const string& strSplit)
{
ClearList();
string strToken;
int pos = 0;
int lastPos = 0;
pos = strStringList.find(strSplit, lastPos);
while (pos != -1)
{
if ((pos - lastPos) >= 1)
{
strToken = strStringList.substr(lastPos, pos - lastPos);
PNode node = new Node;
node->data = strToken;
AppendNode(node);
}
lastPos = pos + strSplit.length();
pos = strStringList.find(strSplit, lastPos);
}
if (pos == -1 && lastPos == 0)
{
PNode node = new Node;
node->data = strStringList;
AppendNode(node);
}
else if (lastPos != 0)
{
long len = strStringList.length();
if (len > lastPos)
{
strToken = strStringList.substr(lastPos, len - lastPos);
PNode node = new Node;
node->data = strToken;
AppendNode(node);
}
}
MoveBegin();
}
string WNCStringList::Join(const char* lpSplit /* = _T */)
{
string strRet("");
for (PNode node = Begin(); node != Head(); node = node->nextNode)
{
if (node != Begin())
{
strRet += lpSplit;
}
strRet += node->data;
}
return strRet;
}
/*utf8解析行 Don't remove or modify this first line!*/
#ifdef __WINOS__
#include "StdAfx.h"
#endif
#include "WNCreticalSection.h"
#include "stdio.h"
class CreticalSectionAttr
{
public:
pthread_mutexattr_t mattr;
public:
CreticalSectionAttr()
{
pthread_mutexattr_init(&mattr);
pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE);
}
~CreticalSectionAttr()
{
pthread_mutexattr_destroy(&mattr);
}
pthread_mutexattr_t* getAttr()
{
return &mattr;
}
};
CreticalSectionAttr mCreticalSectionAttr;
WNCreticalSection::WNCreticalSection(void)
:mpLocker(NULL)
{
CreateLocker();
}
WNCreticalSection::~WNCreticalSection(void)
{
DestroyLocker();
}
void WNCreticalSection::CreateLocker()
{
if (!mpLocker)
{
mpLocker = new pthread_mutex_t;
pthread_mutex_init(mpLocker, mCreticalSectionAttr.getAttr());
}
}
void WNCreticalSection::DestroyLocker()
{
if (mpLocker)
{
pthread_mutex_destroy(mpLocker);
delete mpLocker;
mpLocker = NULL;
}
}
bool WNCreticalSection::TryLock()
{
if (mpLocker)
{
//pthread_mutex_lock(mpLocker);
/*struct timespec lockwait = {0,50000000};
int ret = pthread_mutex_timedlock(mpLocker,&lockwait);
return (ret == 0) ? true : false;*/
int ret = pthread_mutex_trylock(mpLocker);
return (ret == 0) ? true : false;
}
else
{
//没有初始化锁,默认返回TRUE表示可以操作
return true;
}
return true;
}
bool WNCreticalSection::Lock()
{
if (mpLocker)
{
while(pthread_mutex_lock(mpLocker))
{
printf("WNCreticalSection lock failed!");
}
}
//没有初始化锁,默认返回TRUE表示可以操作
return true;
}
bool WNCreticalSection::Unlock()
{
if (mpLocker)
{
pthread_mutex_unlock(mpLocker);
}
return true;
}
WNCreticalSectionAutoLocker::WNCreticalSectionAutoLocker()
:mpLocker(NULL)
,mpLocking(NULL)
{
}
WNCreticalSectionAutoLocker::WNCreticalSectionAutoLocker(WNCreticalSection* pCreiticalSection, bool bLocker /* = TRUE */)
:mpLocker(NULL)
,mpLocking(NULL)
{
mpLocker = pCreiticalSection;
if (bLocker)
{
Lock();
}
}
WNCreticalSectionAutoLocker::~WNCreticalSectionAutoLocker()
{
if (mpLocker && mpLocking)
{
mpLocker->Unlock();
}
}
bool WNCreticalSectionAutoLocker::TryLock()
{
if (mpLocker)
{
if (mpLocking == mpLocker)
{
return true;
}
else if (!mpLocking)
{
if (mpLocker->TryLock())
{
mpLocking = mpLocker;
return true;
}
else
{
mpLocking = NULL;
return false;
}
}
else if (mpLocker->TryLock())
{
mpLocking = mpLocker;
return true;
}
else
{
mpLocking = NULL;
return false;
}
}
else
{
//未设置锁对象
//默认为成功锁定
return true;
}
}
void WNCreticalSectionAutoLocker::Lock()
{
if (mpLocker)
{
if (!mpLocking || (mpLocking != mpLocker))
{
mpLocker->Lock();
mpLocking = mpLocker;
}
}
}
void WNCreticalSectionAutoLocker::Unlock()
{
if (!mpLocker)
{
return;
}
if (mpLocking == mpLocker)
{
mpLocker->Unlock();
}
mpLocking = NULL;
}
/*utf8解析行 Don't remove or modify this first line!*/
//#include "stdafx.h"
#include "WNInvoker.h"
WNInvokeInfo::WNInvokeInfo()
:mbInvoked(FALSE)
,muInvokeTime(0)
,mpReturnValue(NULL)
{
}
WNInvokeInfo::~WNInvokeInfo()
{
Reset();
}
//======================================================================================================
void WNInvokeInfo::Reset()
{
mbInvoked = FALSE;
muInvokeTime = 0;
mpReturnValue = NULL;
}
void WNInvoker::AddInvokeInfo( WNInvokeInfo* pInvokeInfo )
{
if (!pInvokeInfo)
{
return;
}
mInvokeLocker.LockWrite();
if (!mInvokeList.ListCount())
{
pInvokeInfo->Retain();
mInvokeList.AppendNode(pInvokeInfo);
mInvokeLocker.ReleaseWrite();
return;
}
else
{
WNCLoopList<WNInvokeInfo*>::PNode pNode = NULL;
for (mInvokeList.MoveEnd(); mInvokeList.NotHead(); mInvokeList.MovePrev())
{
pNode = mInvokeList.Current();
if (pNode->data->muInvokeTime <= pInvokeInfo->muInvokeTime)
{
pInvokeInfo->Retain();
mInvokeList.AppendNode(pInvokeInfo, pNode);
mInvokeLocker.ReleaseWrite();
return;
}
}
pInvokeInfo->Retain();
mInvokeList.PreAppendNode(pInvokeInfo);
mInvokeLocker.ReleaseWrite();
return;
}
}
BOOL WNInvoker::DoCheckAndInvoke()
{
if (!DoCheckInvoke())
{
return FALSE;
}
if (!DoInvoke())
{
return FALSE;
}
while (DoCheckInvoke())
{
DoInvoke();
}
return TRUE;
}
BOOL WNInvoker::DoCheckInvoke()
{
mInvokeLocker.LockRead();
if (!mInvokeList.ListCount())
{
mInvokeLocker.ReleaseRead();
return FALSE;
}
UINT uCurrentTime = getCurrentTime();
if (mInvokeList.BeginData()->muInvokeTime <= uCurrentTime)
{
mInvokeLocker.ReleaseRead();
return TRUE;
}
else
{
mInvokeLocker.ReleaseRead();
return FALSE;
}
}
BOOL WNInvoker::DoInvoke()
{
mInvokeLocker.LockWrite();
if (!mInvokeList.ListCount())
{
mInvokeLocker.ReleaseWrite();
return FALSE;
}
WNInvokeInfo* pInvokeInfo = mInvokeList.BeginData();
mInvokeList.RemoveNode(mInvokeList.Begin());
pInvokeInfo->InvokeMemberFunc();
pInvokeInfo->Release();
mInvokeLocker.ReleaseWrite();
return TRUE;
}
/*utf8解析行 Don't remove or modify this first line!*/
#include "stdafx.h"
#include "WNNetworkInfo.h"
WNAddrData::WNAddrData()
:m_strAdapterName(_T(""))
,m_strAdapterInfo(_T(""))
,m_strIp(_T("0.0.0.0"))
,m_uMacLen(0)
,m_strVirtualMac(_T(""))
,m_bIsVirtual(FALSE)
,m_uType(0)
,m_nIPCount(0)
{
ZeroMemory(m_MacAddr, MAC_LENGTH);
}
WNAddrData::WNAddrData( const WNAddrData& data )
{
m_strAdapterName = data.m_strAdapterName;
m_strAdapterInfo = data.m_strAdapterInfo;
m_strIp = data.m_strIp;
m_uMacLen = data.m_uMacLen;
m_strVirtualMac = data.m_strVirtualMac;
m_bIsVirtual = data.m_bIsVirtual;
m_uType = data.m_uType;
CopyMemory(m_MacAddr, data.m_MacAddr, MAC_LENGTH);
}
CString WNAddrData::GetMacAddress()
{
if (m_strVirtualMac != _T(""))
{
return m_strVirtualMac;
}
CString strRet = _T("");
CString strCh = _T("");
for (UINT i = 0; i < m_uMacLen; i++)
{
strCh.Format(_T("%02X"), m_MacAddr[i]);
strRet += strCh;
}
return strRet;
}
WNAddrData& WNAddrData::operator=( const WNAddrData& data )
{
if (this == &data)
{
return *this;
}
m_strAdapterName = data.m_strAdapterName;
m_strAdapterInfo = data.m_strAdapterInfo;
m_strIp = data.m_strIp;
m_uMacLen = data.m_uMacLen;
m_strVirtualMac = data.m_strVirtualMac;
m_bIsVirtual = data.m_bIsVirtual;
m_strBroadCastIp = data.m_strBroadCastIp;
m_strSubnetMask = data.m_strSubnetMask;
m_uType = data.m_uType;
m_dwStartIp = data.m_dwStartIp;
m_dwEndIp = data.m_dwEndIp;
m_dwAdapterIndex = data.m_dwAdapterIndex;
m_nIPCount = data.m_nIPCount;
for(int iIndex = 0; iIndex < m_nIPCount; ++iIndex)
m_strIPList[iIndex] = data.m_strIPList[iIndex];
CopyMemory(m_MacAddr, data.m_MacAddr, MAC_LENGTH);
return *this;
}
WNNetworkInfo::WNNetworkInfo()
{
ReInit();
}
VOID WNNetworkInfo::ReInit()
{
WNAddrData macDatas[ADAPTER_COUNT_MAX];
LONG lInsertCount = GetSystemMacInfo(macDatas);
m_lCount = 0;
//for (LONG j = 1; j < lInsertCount; j++)
//{
// if (macDatas[j].m_uType != MIB_IF_TYPE_PPP)
// {
// m_MacData[m_lSystemIdCount] = macDatas[0];
// CopyMemory(m_MacData[m_lSystemIdCount].m_MacAddr, macDatas[j].m_MacAddr, MAC_LENGTH);
// m_MacData[m_lSystemIdCount].m_strIp = macDatas[j].m_strIp;
// m_lSystemIdCount++;
// }
//}
for (LONG i = 0; i < lInsertCount; i++)
{
if (macDatas->m_uType != MIB_IF_TYPE_PPP)
{
m_AddrData[m_lCount] = macDatas[i];
m_lCount++;
}
}
for (LONG i = 0; i < lInsertCount; i++)
{
if (macDatas->m_uType == MIB_IF_TYPE_PPP)
{
for (LONG j = 0; j < lInsertCount; j++)
{
if (macDatas[j].m_uType != MIB_IF_TYPE_PPP)
{
m_AddrData[m_lCount] = macDatas[i];
CopyMemory(m_AddrData[m_lCount].m_MacAddr, macDatas[j].m_MacAddr, MAC_LENGTH);
m_lCount++;
}
}
}
}
}
BOOL WNNetworkInfo::IsConnectedAdapter(DWORD dwIndex)
{
MIB_IFROW ifRow;
ZeroMemory(&ifRow, sizeof(ifRow));
ifRow.dwIndex = dwIndex;
DWORD dwRet = GetIfEntry(&ifRow);
if (dwRet != NO_ERROR)
{
OutputDebugString(_T("GetIfEntry return is not NO_ERROR"));
return FALSE;
}
if (ifRow.dwOperStatus != MIB_IF_OPER_STATUS_OPERATIONAL)
{
OutputDebugString(_T("ifRow.dwOperStatus != MIB_IF_OPER_STATUS_CONNECTED"));
CString strOut;
strOut.Format(_T("State is %d"), ifRow.dwOperStatus);
OutputDebugString(strOut);
return FALSE;
}
return TRUE;
}
//get system Ethernet adapters
LONG WNNetworkInfo::GetSystemMacInfo(WNAddrData* pAddrData)
{
IP_ADAPTER_INFO ipAdapterInfo[ADAPTER_COUNT_MAX];
ULONG uBufferSize = sizeof(IP_ADAPTER_INFO) * ADAPTER_COUNT_MAX;
DWORD dwRet = GetAdaptersInfo(ipAdapterInfo, &uBufferSize);
if (ERROR_SUCCESS != dwRet)
{
return FALSE;
}
//Add a virtual networkcard at first
//pMacData->m_strAdapterName = _T("E Virtual NetworkCard");
//pMacData->m_bIsVirtual = TRUE;
//pMacData++;
LONG lRet = 0;
PIP_ADAPTER_INFO pInfo = ipAdapterInfo;
PIP_ADDR_STRING pIpInfo = &(pInfo->IpAddressList);
while (pInfo)
{
if (MIB_IF_TYPE_ETHERNET == pInfo->Type || MIB_IF_TYPE_PPP == pInfo->Type || TRUE)
{
if (IsConnectedAdapter(pInfo->Index) || MIB_IF_TYPE_PPP == pInfo->Type)
{
pAddrData->m_dwAdapterIndex = pInfo->Index;
CopyMemory(pAddrData->m_MacAddr, pInfo->Address, pInfo->AddressLength);
pAddrData->m_uMacLen = pInfo->AddressLength;
LPTSTR pBuf = pAddrData->m_strAdapterInfo.GetBuffer(sizeof(pInfo->Description) * sizeof(TCHAR));
//pMacData->m_strAdapterInfo.Format(_T("%s"), pInfo->Description);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pInfo->Description, -1, pBuf, sizeof(pInfo->Description));
pAddrData->m_strAdapterInfo.ReleaseBuffer();
pBuf = pAddrData->m_strAdapterName.GetBuffer(sizeof(pInfo->AdapterName) * sizeof(TCHAR));
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pInfo->AdapterName, -1, pBuf, sizeof(pInfo->AdapterName));
pAddrData->m_strAdapterName.ReleaseBuffer();
pBuf = pAddrData->m_strIp.GetBuffer(sizeof(pIpInfo->IpAddress) * sizeof(TCHAR));
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pIpInfo->IpAddress.String, -1, pBuf, sizeof(pIpInfo->IpAddress.String) * sizeof(TCHAR));
pAddrData->m_strIp.ReleaseBuffer();
pBuf = pAddrData->m_strSubnetMask.GetBuffer(sizeof(pIpInfo->IpMask) * sizeof(TCHAR));
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pIpInfo->IpMask.String, -1, pBuf, sizeof(pIpInfo->IpMask.String) * sizeof(TCHAR));
pAddrData->m_strSubnetMask.ReleaseBuffer();
in_addr broadcast;
broadcast.S_un.S_addr = (inet_addr( CT2A(pAddrData->m_strIp))
& inet_addr( CT2A(pAddrData->m_strSubnetMask)))
| (~inet_addr( CT2A(pAddrData->m_strSubnetMask)));
pAddrData->m_strBroadCastIp = inet_ntoa(broadcast);
pAddrData->m_dwStartIp = (ntohl(inet_addr( CT2A(pAddrData->m_strSubnetMask))) & ntohl(inet_addr( CT2A(pAddrData->m_strIp)))) + 1;
pAddrData->m_dwEndIp = ntohl(inet_addr( CT2A(pAddrData->m_strBroadCastIp) )) - 1;
if((pAddrData->m_dwEndIp - pAddrData->m_dwStartIp) > 1000)
{
pAddrData->m_dwEndIp = pAddrData->m_dwStartIp + 1000;
}
pAddrData->m_uType = pInfo->Type;
OutputDebugStringV(pAddrData->m_strAdapterName);
OutputDebugStringV(pAddrData->m_strAdapterInfo);
OutputDebugStringV(pAddrData->GetMacAddress());
OutputDebugStringV(pAddrData->m_strIp);
if(!pAddrData->m_strIp.IsEmpty())
{
pAddrData->m_strIPList[pAddrData->m_nIPCount] = pAddrData->m_strIp;
++pAddrData->m_nIPCount;
}
if (pIpInfo->Next)
{
pIpInfo = pIpInfo->Next;
}
else
{
pInfo = pInfo->Next;
pIpInfo = &(pInfo->IpAddressList);
}
lRet++;
pAddrData++;
}
else
{
pInfo = pInfo->Next;
pIpInfo = &(pInfo->IpAddressList);
}
}
else
{
pInfo = pInfo->Next;
pIpInfo = &(pInfo->IpAddressList);
}
}
return lRet;
}
WNAddrData* WNNetworkInfo::GetAdapterInfo(LONG lIndex)
{
if (lIndex >= m_lCount)
{
return NULL;
}
else
{
return &m_AddrData[lIndex];
}
}
VOID WNNetworkInfo::SetVirtualMac( CString& strMac )
{
OutputDebugStringV(_T("SetVirtualMac %s"), strMac);
for (LONG i = 0; i < m_lCount; i++)
{
m_AddrData[i].m_strVirtualMac = strMac;
}
}
void WNNetworkInfo::OutputAdapterInfo()
{
for (int i = 0; i < m_lCount; i++)
{
OutputDebugStringV(_T("Adapter %d:"), i);
OutputDebugStringV(_T("Name is %s, VirtualMac is %d"), m_AddrData[i].m_strAdapterName, m_AddrData[i].IsVirtual());
OutputDebugStringV(_T("Ip is %s"), m_AddrData[i].m_strIp);
OutputDebugStringV(_T("MacAddress is %s"), m_AddrData[i].GetMacAddress());
}
}
\ No newline at end of file
/*utf8解析行 Don't remove or modify this first line!*/
#ifdef __WINOS__
#include "stdafx.h"
#endif
#include "WNObject.h"
#include "WNCreticalSection.h"
#include "stdio.h"
#define InitRefCount 0x3FFFFFFF
WNObject::WNObject()
:miRetainCount(InitRefCount)
,mbIsAllocOnHeap(false)
,miDelayReleaseCount(0)
,mpDelegate(NULL)
,mpLoker(NULL)
,mbIsOwnLocker(false)
,mpThis(NULL)
,mpTypeFn(NULL)
{
}
WNObject::~WNObject()
{
ResetSafeLocker();
}
void WNObject::ResetRefInfo()
{
miRetainCount = InitRefCount;
miDelayReleaseCount = 0;
}
void WNObject::ResetRefInfoAndDelegate( WNObjectDelegate* pDelegate /*= NULL*/ )
{
ResetRefInfo();
mpDelegate = pDelegate;
}
void WNObject::SetSafeLocker( WNCreticalSection* pLocker /*= NULL*/ )
{
ResetSafeLocker();
if (pLocker)
{
mpLoker = pLocker;
}
else
{
mpLoker = new WNCreticalSection;
mbIsOwnLocker = true;
}
}
WNCreticalSection* WNObject::GetSafeLocker()
{
return mpLoker;
}
void WNObject::ResetSafeLocker()
{
if (mpLoker)
{
if (mbIsOwnLocker)
{
delete mpLoker;
}
mpLoker = NULL;
mbIsOwnLocker = false;
}
}
WNObject* WNObject::Retain()
{
WNCreticalSectionAutoLocker locker(mpLoker);
if (miRetainCount == InitRefCount)
{
miRetainCount = 1;
}
else
{
miRetainCount++;
}
return this;
}
WNSmartPtr<WNObject*> WNObject::AutoRelease()
{
WNCreticalSectionAutoLocker locker(mpLoker);
return WNSmartPtr<WNObject*>(this->DelayRelease());
}
WNObject* WNObject::Release( bool bClearDelayRelease /*= true*/ )
{
if (bClearDelayRelease)
{
WNCreticalSectionAutoLocker locker(mpLoker);
int iRetainCount = 0;
int iDelayReleaseCount = 0;
int iOldRefCount = 0;
int iNewRefCount = 0;
bool bIsChangeZero = false;
iRetainCount = miRetainCount;
if (iRetainCount == InitRefCount)
{
iRetainCount = 1;
}
iDelayReleaseCount = miDelayReleaseCount;
iOldRefCount = iRetainCount - iDelayReleaseCount;
if (iOldRefCount < 0)
{
printf("error 0 WNObject %p, RefCount is %d", this, iOldRefCount);
iOldRefCount = 0;
return NULL;
}
else if (!iOldRefCount)
{
if (iDelayReleaseCount)
{
iNewRefCount = 0;
bIsChangeZero = true;
printf("warning 0 WNObject %p, RefCount is %d", this, iOldRefCount);
}
else
{
printf("error 1 WNObject %p, RefCount is %d", this, iOldRefCount);
return NULL;
}
}
else
{
iNewRefCount = iOldRefCount - 1;
if (!iNewRefCount)
{
bIsChangeZero = true;
}
}
if (!bIsChangeZero)
{
miRetainCount = iNewRefCount;
miDelayReleaseCount = 0;
return this;
}
else
{
//need delete or free by mpDelegate
WNObject* pObject = this;
if (mpDelegate)
{
if (!mpDelegate->OnWNObjectRetainCountIsZero(this))
{
//freed by mpDelegate
pObject = NULL;
}
}
if (pObject)
{
if (mbIsAllocOnHeap)
{
ResetSafeLocker();
locker.mpLocker = NULL;
WNObjectTypeFnBase* pTypeFn = this->mpTypeFn;
void* pThis = this->mpThis;
if (pTypeFn && pThis)
{
pTypeFn->DoDestroy(pThis);
}
else
{
delete this;
}
}
}
return NULL;
}
}
else
{
WNCreticalSectionAutoLocker locker(mpLoker);
miRetainCount--;
return this;
}
}
WNObject* WNObject::DelayRelease()
{
WNCreticalSectionAutoLocker locker(mpLoker);
if (miRetainCount == InitRefCount)
{
miRetainCount = 1;
miDelayReleaseCount = 1;
}
else if (miRetainCount)
{
miDelayReleaseCount++;
if (miDelayReleaseCount > miRetainCount)
{
miDelayReleaseCount = miRetainCount;
}
}
else
{
miRetainCount = 1;
miDelayReleaseCount = 1;
}
return this;
}
WNObject* WNObject::ClearDelayRelease( bool bOlnySetZero /*= FALSE*/ )
{
WNCreticalSectionAutoLocker locker(mpLoker);
if (miRetainCount == InitRefCount)
{
//初始化状态
miDelayReleaseCount = 0;
if (mpDelegate)
{
if (!mpDelegate->OnWNObjectRetainCountIsZero(this))
{
return this;
}
}
return NULL;
}
int iOldRetainCount = miRetainCount;
if (!bOlnySetZero)
{
miRetainCount -= miDelayReleaseCount;
}
miDelayReleaseCount = 0;
if (!miRetainCount && (miRetainCount != iOldRetainCount))
{
if (mpDelegate)
{
if (!mpDelegate->OnWNObjectRetainCountIsZero(this))
{
return this;
}
}
return NULL;
}
return this;
}
//void _doRelease( WNObject** ppObj )
//{
// if (*ppObj)
// {
// (*ppObj)->Release();
// *ppObj = NULL;
// }
//}
//
//void _doDelayRelease( WNObject** ppObj )
//{
// if (*ppObj)
// {
// (*ppObj)->DelayRelease();
// *ppObj = NULL;
// }
//}
/*utf8解析行 Don't remove or modify this first line!*/
#ifdef __WINOS__
#include "stdafx.h"
#endif
#include "WNReadWriteLocker.h"
#include "WNCreticalSection.h"
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
long getCurrentTime()
{
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
WNReadWriteLocker::WNReadWriteLocker()
:m_dwReadCount(0)
,m_dwWriteCount(0)
,m_bWriting(false)
{
mpLocker = new WNCreticalSection;
}
WNReadWriteLocker::~WNReadWriteLocker()
{
delete mpLocker;
mpLocker = 0;
}
bool WNReadWriteLocker::LockRead(unsigned long dwTimeOut /* = 0 */)
{
if (!dwTimeOut)
{
//超时为零,等待直到设置读状态成功
while (!InternalLockRead())
{
usleep(1000);
}
return true;
}
else
{
//超时为非零,等待直到设置读状态成功或者超时
unsigned long dwStart = getCurrentTime();
if (!InternalLockRead())
{
usleep(1000);
}
else
{
return true;
}
while (!InternalLockRead())
{
if (getCurrentTime() - dwStart > dwTimeOut)
{
return false;
}
usleep(1000);
}
return true;
}
}
bool WNReadWriteLocker::LockWrite(unsigned long dwTimeOut /* = 0 */)
{
mpLocker->Lock();
m_dwWriteCount++;
long dlTimeout = dwTimeOut;
mpLocker->Unlock();
if (!dwTimeOut)
{
//超时为零,等待直到设置写状态成功
while (!InternalLockWrite())
{
usleep(1000);
}
return true;
}
else
{
//超时为非零,等待直到设置写状态成功或者超时
long dwStart = getCurrentTime();
if (!InternalLockWrite())
{
usleep(1000);
}
else
{
return true;
}
while (!InternalLockWrite())
{
if (getCurrentTime() - dwStart > dlTimeout)
{
mpLocker->Lock();
m_dwWriteCount--;
mpLocker->Unlock();
return false;
}
usleep(1000);
}
return true;
}
}
bool WNReadWriteLocker::ReleaseRead()
{
mpLocker->Lock();
m_dwReadCount--;
mpLocker->Unlock();
return true;
}
bool WNReadWriteLocker::ReleaseWrite()
{
mpLocker->Lock();
m_dwWriteCount--;
m_bWriting = false;
mpLocker->Unlock();
return true;
}
bool WNReadWriteLocker::InternalLockRead()
{
mpLocker->Lock();
if (!m_dwWriteCount)
{
m_dwReadCount++;
mpLocker->Unlock();
return true;
}
else
{
mpLocker->Unlock();
return false;
}
}
bool WNReadWriteLocker::InternalLockWrite()
{
mpLocker->Lock();
if (m_dwReadCount)
{
mpLocker->Unlock();
return false;
}
else if (m_bWriting)
{
mpLocker->Unlock();
return false;
}
else
{
m_bWriting = true;
mpLocker->Unlock();
return true;
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment