編輯:關於 Android 程式設計
既然選擇用 RakNet 做網路層,就不能只停在「會呼叫 API」的階段。把源碼結構、資料結構與各個插件的職責摸清楚,後續要擴充、要調效能、要排查奇怪的連線問題時才有底氣。本文是 RakNet 系列的最後一篇,重點放在源碼說明。
RakNet 的 Source 目錄檔案數量相當可觀,但依職責大致可以歸成以下幾類:
· 核心連線:RakPeer、RakPeerInterface、ReliabilityLayer、RakNetSocket(2)、SocketLayer、NetworkIDManager、NetworkIDObject
· 資料傳輸與序列化:BitStream、InternalPacket、PacketPriority、PacketPool、CCRakNetSlidingWindow、CCRakNetUDT
· 容器(DataStructures):DS_BinarySearchTree、DS_BPlusTree、DS_Hash、DS_Heap、DS_LinkedList、DS_List、DS_Map、DS_Multilist、DS_OrderedList、DS_Queue、DS_Tree、DS_WeightedGraph 等
· 編碼與壓縮:Base64Encoder、DR_SHA1、DS_HuffmanEncodingTree 系列、StringCompressor、DataCompressor、SuperFastHash、CheckSum
· 位元組與字串輔助:DS_BytePool、DS_ByteQueue、FormatString、RakString、RakWString、StringTable、EpochTimeToString
· 記憶體管理:RakMemoryOverride、RakAlloca、RakAssert、RakNetSmartPtr、DS_MemoryPool、RefCountedObj
· 檔案與更新:FileList、FileListTransfer、FileListTransferCBInterface、DirectoryDeltaTransfer、AutopatcherRepositoryInterface、_FindFirst
· 連線與路由插件:Router2、FullyConnectedMesh2、ConnectionGraph2、RelayPlugin、UDPForwarder
· NAT 相關:NatPunchthroughClient / Server、NatTypeDetectionClient / Server / Common、UDPProxyClient / Coordinator / Server
· 雲端與副本:CloudClient、CloudServer、CloudCommon、ReplicaManager3、Replica3
· 安全性:SecureHandshake、TwoWayAuthentication、MessageFilter、RPC4Plugin
· 傳輸與協議:TCPInterface、PacketizedTCP、HTTPConnection(2)、TelnetTransport、RakNetTransport2、ConsoleServer
· 平台與工具:NativeTypes、WindowsIncludes、VitaIncludes、Xbox360Includes、ThreadsafePacketLogger、LogCommandParser、EmailSender、DynDNS、TeamManager
與編碼相關的檔案有 Base64Encoder、DR_SHA1、DS_HuffmanEncodingTree、DS_HuffmanEncodingTreeFactory、DS_HuffmanEncodingTreeNode。
Base64Encoder 只對外兩個函數:
extern "C" {
/// \brief 回傳實際寫入的字節數
// outputData 的容量至少要 inputData 大小 * 2 + 6
int Base64Encoding(const unsigned char *inputData, int dataLength, char *outputData);
}
extern "C" {
const char *Base64Map(void);
}
DR_SHA1 用於數位簽章標準,官方測試向量如下:
SHA1("abc" in ANSI) = A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
SHA1("abc" in Unicode LE) = 9F04F41A 84851416 2050E3D6 8C1A7ABB 441DC2B5
SHA1("abcdbcdecdef...nopq" in ANSI) = 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
SHA1(A million "a" in ANSI) = 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
DS_HuffmanEncodingTree 系列 負責哈夫曼編碼。哈夫曼編碼(Huffman Coding)由 Huffman 於 1952 年提出,是一種變長碼(VLC):完全依據字元出現機率構造出平均長度最短的碼字,因此又被稱為最佳編碼。節點結構如下:
struct HuffmanEncodingTreeNode {
unsigned char value;
unsigned weight;
HuffmanEncodingTreeNode *left;
HuffmanEncodingTreeNode *right;
HuffmanEncodingTreeNode *parent;
};
容器負責管理物件生命週期與物件之間的依賴關係。RakNet 自帶了一套 DS_* 容器,並區分同步/非同步、執行緒安全/非安全。
DS_BinarySearchTree(二叉排序樹):左子樹所有節點值小於根節點,右子樹所有節點值大於根節點,左右子樹本身也是二叉排序樹。
* EXAMPLE * @code * BinarySearchTree<int> A; * A.Add(10); * A.Add(15); * A.Add(5); * int* array = RakNet::OP_NEW<int>(A.Size(), _FILE_AND_LINE_); * A.DisplayInorder(array); * array[0]; // returns 5 * array[1]; // returns 10 * array[2]; // returns 15
DS_BPlusTree:每個節點最多有兩個子樹的有序樹。插入與刪除後都需呼叫 ValidateTree() 驗證結構正確性:
DataStructures::BPlusTree<int, int, 16> btree; btree.Insert(key, value); btree.ValidateTree(); btree.Delete(key); bool b; b = btree.Get(key, temp); RakAssert(btree.Size() == haveList.Size());
DS_Hash:把任意長度的輸入經散列演算法映射成固定長度輸出。常見的雜湊建構方法有直接取餘法、乘法取整法與平方取中法:
// 直接取餘法:f(x) := x mod maxM ; maxM 一般取不太接近 2^t 的質數 // 乘法取整法:f(x) := trunc((x/maxX)*maxlongit) mod maxM,主要用於實數 // 平方取中法:f(x) := (x*x div 1000) mod 1000000,取中間位,資訊含量較高
struct HashIndex {
unsigned int primaryIndex;
unsigned int secondaryIndex;
bool IsInvalid(void) const { return primaryIndex == (unsigned int) -1; }
void SetInvalid(void) {
primaryIndex = (unsigned int) -1;
secondaryIndex = (unsigned int) -1;
}
};
DS_Heap:一種特殊的樹形結構,滿足父節點值必定大於或等於子節點值。DS_OrderedChannelHeap 為其有序通道版本。
struct HeapNode {
HeapNode() {}
HeapNode(const weight_type &w, const data_type &d) : weight(w), data(d) {}
weight_type weight; // key 需為 float 或 int 等原生數值型別
data_type data;
};
DS_LinkedList:鏈表,支援插入、查找、替換、刪除、排序與環形變體 CircularLinkedList。
LinkedList<int> A; A.Insert(20); // A: 20 - current is 20 A.Insert(5); // A: 5 20 - current is 5 A.IsIn(1); // returns true A.Find(5); // returns true and sets current to 5 A.Peek(); // returns 5 (++A).Peek(); // Returns 5 A.Replace(10); // Replaces 5 with 10 A.Del(); // Deletes 10, current points to the next element A.Clear(_FILE_AND_LINE_);
DS_List、DS_Multilist、DS_OrderedList、DS_RangeList、DS_QueueLinkedList 用法同類。
DS_Map:鍵值對容器,內部以「上次搜尋索引 + 上次搜尋鍵」做快取加速重複查詢。
lastSearchIndex = index; lastSearchKey = key; lastSearchIndexValid = true;
struct MapNode {
MapNode() {}
MapNode(key_type _key, data_type _data) : mapNodeKey(_key), mapNodeData(_data) {}
MapNode& operator = (const MapNode& input) {
mapNodeKey = input.mapNodeKey;
mapNodeData = input.mapNodeData;
return *this;
}
MapNode(const MapNode &input) {
mapNodeKey = input.mapNodeKey;
mapNodeData = input.mapNodeData;
}
key_type mapNodeKey;
data_type mapNodeData;
};
DS_Queue:佇列。DS_ThreadsafeAllocatingQueue 是其執行緒安全版本(內部加了鎖)。DS_Tree 則是通用樹結構:
template <class TreeType>
class RAK_DLL_EXPORT Tree {
public:
Tree();
Tree(TreeType &inputData);
~Tree();
void LevelOrderTraversal(DataStructures::List<TreeType> &output);
void AddChild(TreeType &newData);
void DeleteDecendants(void);
TreeType data;
DataStructures::List<Tree<TreeType>*> children;
};
DS_BytePool:位元組池,以分級內存池(128 / 512 / 2048 / 8192)管理位元組的申請與釋放,顯著降低反覆配置的成本。
class RAK_DLL_EXPORT BytePool {
public:
BytePool();
~BytePool();
// 建議至少為 8192 的 8 倍
void SetPageSize(int size);
unsigned char* Allocate(int bytesWanted, const char *file, unsigned int line);
void Release(unsigned char *data, const char *file, unsigned int line);
void Clear(const char *file, unsigned int line);
protected:
MemoryPool<unsigned char[128]> pool128;
MemoryPool<unsigned char[512]> pool512;
MemoryPool<unsigned char[2048]> pool2048;
MemoryPool<unsigned char[8192]> pool8192;
#ifdef _THREADSAFE_BYTE_POOL
SimpleMutex mutex128, mutex512, mutex2048, mutex8192;
#endif
};
DS_ByteQueue:位元組佇列,提供寫入、讀取與 peek 操作,並以 readOffset / writeOffset 兩個游標維護位置。
class ByteQueue {
public:
ByteQueue();
~ByteQueue();
void WriteBytes(const char *in, unsigned length, const char *file, unsigned int line);
bool ReadBytes(char *out, unsigned maxLengthToRead, bool peek);
unsigned GetBytesWritten(void) const;
char* PeekContiguousBytes(unsigned int *outLength) const;
void IncrementReadOffset(unsigned length);
void DecrementReadOffset(unsigned length);
void Clear(const char *file, unsigned int line);
void Print(void);
protected:
char *data;
unsigned readOffset, writeOffset, lengthAllocated;
};
相關檔案:FormatString、LinuxStrings、RakString、RakWString、StringCompressor、StringTable、EpochTimeToString。
FormatString 提供格式化輸出,並有執行緒安全版本:
extern "C" {
// 格式化輸出
char *FormatString(const char *format, ...);
}
// Threadsafe
extern "C" {
char *FormatStringTS(char *output, const char *format, ...);
}
LinuxStrings 為非 Windows 平台補上 MSVC 專用的字串函數:
#if (defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__)) && !defined(_WIN32)
#ifndef _stricmp
int _stricmp(const char* s1, const char* s2);
#endif
int _strnicmp(const char* s1, const char* s2, size_t n);
#define _vsnprintf vsnprintf
#ifndef __APPLE__
char *_strlwr(char *str);
#endif
#endif
RakString / RakWString 是自字字串類別,重載了大量運算子並內建格式化能力;StringCompressor 負責字串壓縮,內部以哈夫曼編碼樹管理:
/// 指向哈夫曼編碼樹 DataStructures::Map<int, HuffmanEncodingTree *> huffmanEncodingTrees;
StringTable 負責字串的編碼與解碼(以索引代替重複字串傳輸);EpochTimeToString 則把時間戳轉為可讀字串:
int RAK_DLL_EXPORT StrAndBoolComp(char *const &key, const StrAndBool &data); RAK_DLL_EXPORT char *EpochTimeToString(long long time);
涉及檔案:RakNetSmartPtr、RakAlloca、RakAssert、RakMemoryOverride,負責指標與記憶體生命週期管理。
RakNetSmartPtr 以引用計數實作智能指標:
class RAK_DLL_EXPORT ReferenceCounter {
private:
int refCount;
public:
ReferenceCounter() { refCount = 0; }
~ReferenceCounter() {}
void AddRef() { refCount++; }
int Release() { return --refCount; }
int GetRefCount(void) const { return refCount; }
};
RakMemoryOverride 對外公開一組可替換的配置函數指標,讓整庫的記憶體配置行為完全可控——這是嵌入式與遊戲主機開發中很實用的一點:
extern RAK_DLL_EXPORT void * (*rakMalloc) (size_t size); extern RAK_DLL_EXPORT void * (*rakRealloc) (void *p, size_t size); extern RAK_DLL_EXPORT void (*rakFree) (void *p); extern RAK_DLL_EXPORT void * (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line); extern RAK_DLL_EXPORT void (*notifyOutOfMemory) (const char *file, const long line); extern RAK_DLL_EXPORT void * (*dlMallocMMap) (size_t size); // 替換為自訂配置函數 void RAK_DLL_EXPORT SetMalloc(void* (*userFunction)(size_t size)); void RAK_DLL_EXPORT SetRealloc(void* (*userFunction)(void *p, size_t size)); void RAK_DLL_EXPORT SetFree(void (*userFunction)(void *p)); void RAK_DLL_EXPORT SetMalloc_Ex(void* (*userFunction)(size_t size, const char *file, unsigned int line)); void RAK_DLL_EXPORT SetNotifyOutOfMemory(void (*userFunction)(const char *file, const long line));
_FindFirst:檔案快速查找,對應系統 API。
long _findfirst(const char *name, _finddata_t *f); int _findnext(long h, _finddata_t *f); int _findclose(long h);
SuperFastHash:快速雜湊,支援增量與檔案版本。
uint32_t SuperFastHash(const char *data, int length); uint32_t SuperFastHashIncremental(const char *data, int len, unsigned int lastHash); uint32_t SuperFastHashFile(const char *filename); uint32_t SuperFastHashFilePtr(FILE *fp);
CheckSum:校驗和計算。
class CheckSum {
public:
CheckSum() { Clear(); }
void Clear() { sum = 0; r = 55665; c1 = 52845; c2 = 22719; }
void Add(unsigned int w);
void Add(unsigned short w);
void Add(unsigned char* b, unsigned int length);
void Add(unsigned char b);
unsigned int Get() { return sum; }
protected:
unsigned short r, c1, c2;
unsigned int sum;
};
LocklessUint32_t / RefCountedObj:無鎖計數與引用計數,用於物件生命週期管理。值得注意的是 Android、iOS 等平台上 __sync_fetch_and_add 支援不完整,因此退回使用 mutex:
class RAK_DLL_EXPORT LocklessUint32_t {
public:
LocklessUint32_t();
explicit LocklessUint32_t(uint32_t initial);
uint32_t Increment(void); // 回傳變更後的值
uint32_t Decrement(void);
uint32_t GetValue(void) const { return value; }
protected:
#ifdef _WIN32
volatile LONG value;
#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__)
SimpleMutex mutex;
uint32_t value;
#else
volatile uint32_t value;
#endif
};
class RefCountedObj {
public:
RefCountedObj() { refCount = 1; }
virtual ~RefCountedObj() {}
void AddRef(void) { refCount++; }
void Deref(void) { if (--refCount == 0) RakNet::OP_DELETE(this, _FILE_AND_LINE_); }
int refCount;
};
此外,ThreadPool / RakThread 負責執行緒管理與封裝,Getche、Gets、GetTime、gettimeofday、Itoa、Kbhit、RakNetTime 為系統函數封裝,DS_Table 則是資料表操作。
RakNet 內部保留了一批帶外(Out Of Band)識別碼,用於 NAT 相關流程與主機平台功能:
enum OutOfBandIdentifiers {
ID_NAT_ESTABLISH_UNIDIRECTIONAL, // 單向穿透
ID_NAT_ESTABLISH_BIDIRECTIONAL, // 雙向穿透
ID_NAT_TYPE_DETECT, // 匹配類型
ID_ROUTER_2_REPLY_TO_SENDER_PORT, // 路由器延遲發送端口
ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, // 特定端口
ID_ROUTER_2_MINI_PUNCH_REPLY, // 回復
ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, // 反彈
ID_XBOX_360_VOICE, // 聲音
ID_XBOX_360_GET_NETWORK_ROOM, // 獲取網絡房間
ID_XBOX_360_RETURN_NETWORK_ROOM, // 返回網絡房間
ID_NAT_PING, // ping 測試
ID_NAT_PONG // pong 測試
};
DefaultMessageIDTypes 中都是內部訊息 ID。要新增自定義 ID,從 ID_USER_PACKET_ENUM 之後接續即可:
enum {
ID_MYPROJECT_MSG_1 = ID_USER_PACKET_ENUM,
ID_MYPROJECT_MSG_2,
...
};
BitStream 用一個封裝的動態陣列來打包與解包 bits,四個主要優勢:動態建立資料報、資料壓縮、按位寫入、位元組序轉換。
它是樣板類別,可容納任何型別。對內建型別(如 NetworkIDObject)透過部分樣板特化讓寫入更有效率;對自訂型別或結構體,則可逐位元組寫入記憶體資料。
struct MyVector { // 寫入資料
float x, y, z;
} myVector;
bitStream.Write(myVector); // 沒有位元組序交換
#undef __BITSTREAM_NATIVE_END // 帶有位元組序交換
bitStream.Write(myVector.x);
bitStream.Write(myVector.y);
bitStream.Write(myVector.z);
// 也可以重載運算子
namespace RakNet {
RakNet::BitStream& operator << (RakNet::BitStream& out, MyVector& in) {
out.WriteNormVector(in.x, in.y, in.z);
return out;
}
RakNet::BitStream& operator >> (RakNet::BitStream& in, MyVector& out) {
bool success = in.ReadNormVector(out.x, out.y, out.z);
assert(success);
return in;
}
}
myVector << bitStream; // 向 bitstream 寫入
myVector >> bitStream; // 從 bitstream 讀取
可選做法:BitStream 的某個建構子接受長度參數。若大概知道資料量,在建構時傳入可避免後續動態重配置記憶體。
// 假設我們收到一個封包
Packet *packet = ...;
BitStream myBitStream(packet->data, packet->length, false);
struct MyVector { float x, y, z; } myVector;
bitStream.Read(myVector); // 沒有位元組序轉換
#undef __BITSTREAM_NATIVE_END // 需轉換位元組序時
bitStream.Read(myVector.x);
bitStream.Read(myVector.y);
bitStream.Read(myVector.z);
序列化:Read 與 Write 常用同一組程式碼時,可用 BitStream::Serialize() 合併,只需實作一次:
struct MyVector {
float x, y, z;
// ToBitstream == true 為寫入,false 為讀取
void Serialize(bool writeToBitstream, BitStream *bs) {
bs->Serialize(writeToBitstream, x);
bs->Serialize(writeToBitstream, y);
bs->Serialize(writeToBitstream, z);
}
} myVector;
實際搭配 RPC 使用時,直接在參數中取用 input 位元流即可:
struct EmploymentStruct {
int salary;
unsigned char yearsEmployed;
};
void clientRPC(RPCParameters *rpcParameters) {
BitStream b(rpcParameters->input,
BITS_TO_BYTES(rpcParameters->numberOfBitsOfData), false);
char name[200];
unsigned char nameLength;
b.Read(nameLength);
if (b.Read(name, nameLength) == false) {
printf("Name was not null-terminated!\n");
return;
}
name[nameLength] = 0;
printf("Name is %s\n", name);
unsigned int age;
if (b.ReadCompressed(age) == false) return;
printf("Age is %i\n", age);
bool wroteEmploymentStruct;
if (b.Read(wroteEmploymentStruct) == false) return;
if (wroteEmploymentStruct) {
EmploymentStruct employmentStruct;
if (b.Read(employmentStruct.salary) == false) return;
if (b.Read(employmentStruct.yearsEmployed) == false) return;
}
quit = true;
}
注意註解中提到的重點:直接把整個結構體寫進 BitStream 是不可攜的,因為不同 CPU 的位元組序不同、編譯器對結構體的 padding 也不同。唯一安全的做法是逐成員寫入。
對使用者暴露的封包結構:
struct Packet {
/// 發送此封包的系統位址
SystemAddress systemAddress;
/// 發送者的唯一標識,不受 IP 變動影響
/// 連線建立後(ID_CONNECTION_REQUEST_ACCEPTED 或 ID_NEW_INCOMING_CONNECTION)才有效
/// 在此之前為 UNASSIGNED_RAKNET_GUID
RakNetGUID guid;
unsigned int length; // 資料長度(位元組)
BitSize_t bitSize; // 資料長度(位元)
unsigned char* data; // 封包內容
bool deleteData; // @internal
bool wasGeneratedLocally; // @internal,true 表示不經過插件
};
內部則用 InternalPacket 承載可靠傳輸所需的一切資訊:
typedef uint16_t SplitPacketIdType; // 分包標識型別
typedef uint32_t SplitPacketIndexType; // 分包序號型別
// 封包序號計數器,需大到迴繞後舊值已不再使用;內部假設 4 位元組,寫入時僅用 3 位元組
typedef uint24_t MessageNumberType;
// 有序封包計數器,用於偵測亂序
typedef MessageNumberType OrderingIndexType;
typedef RakNet::TimeUS RemoteSystemTimeType;
struct InternalPacketFixedSizeTransmissionHeader {
MessageNumberType reliableMessageNumber; // 可靠訊息的唯一編號
OrderingIndexType orderingIndex; // 排序識別
OrderingIndexType sequencingIndex; // 僅用於 sequenced 訊息
unsigned char orderingChannel; // 順序通道
SplitPacketIdType splitPacketId; // 分包標識
SplitPacketIndexType splitPacketIndex; // 分包序號
SplitPacketIndexType splitPacketCount; // 分包總數
BitSize_t dataBitLength; // 資料長度
PacketReliability reliability; // 可靠性演算法
};
struct InternalPacketRefCountedData {
unsigned char *sharedDataBlock;
unsigned int refCount;
};
struct InternalPacket : public InternalPacketFixedSizeTransmissionHeader {
MessageNumberType messageInternalOrder; // 本地唯一標識
bool messageNumberAssigned; // 是否已分配編號
RakNet::TimeUS creationTime; // 建立時間
RakNet::TimeUS nextActionTime; // 下次動作時間
RakNet::TimeUS retransmissionTime; // 重送時間(除錯用)
BitSize_t headerLength; // 編碼後的標頭長度
unsigned char *data; // 資料內容
enum AllocationScheme {
NORMAL, // 以 rakMalloc 配置,直接 free
REF_COUNTED, // data 指向更大的區塊,以引用計數管理
STACK // data 指向 stackData,不應釋放(僅用於發送)
} allocationScheme;
InternalPacketRefCountedData *refCountedData;
unsigned char timesSent; // 已嘗試發送次數
PacketPriority priority; // 優先級
uint32_t sendReceiptSerial; // 可靠性回執編號
// 重送佇列(鏈表實作,可用指標直接移除)
InternalPacket *resendPrev, *resendNext, *unreliablePrev, *unreliableNext;
unsigned char stackData[128]; // 堆疊資料
};
typedef uint64_t NetworkID;
struct RAK_DLL_EXPORT RakNetGUID {
RakNetGUID();
explicit RakNetGUID(uint64_t _g) { g = _g; systemIndex = (SystemIndex) -1; }
uint64_t g;
const char *ToString(void) const; // 回傳靜態字串,非執行緒安全
void ToString(char *dest) const; // 執行緒安全
bool FromString(const char *source);
static unsigned long ToUint32(const RakNetGUID &g);
SystemIndex systemIndex; // 內部快速查找用,不可傳輸(-1 表示一般查找)
static int size() { return (int) sizeof(uint64_t); }
bool operator== (const RakNetGUID& right) const;
bool operator!= (const RakNetGUID& right) const;
bool operator> (const RakNetGUID& right) const;
bool operator< (const RakNetGUID& right) const;
};
NetworkIDObject 讓自訂物件能被網路唯一標識。與舊版不同,ID 由 manager 類別配置而非靜態變數,因此同一系統上可以存在多組獨立的 ID 空間:
class RAK_DLL_EXPORT NetworkIDObject {
public:
NetworkIDObject();
virtual ~NetworkIDObject();
virtual void SetNetworkIDManager(NetworkIDManager *manager); // 綁定管理
virtual NetworkIDManager *GetNetworkIDManager(void) const;
virtual NetworkID GetNetworkID(void); // 取得 id(0-65534 為有效值)
virtual void SetNetworkID(NetworkID id);
virtual void SetParent(void *_parent); // 不繼承時可指定父物件
virtual void* GetParent(void) const;
protected:
NetworkID networkID;
NetworkIDManager *networkIDManager;
void *parent;
friend class NetworkIDManager;
NetworkIDObject *nextInstanceForNetworkIDManager;
};
RakNet 幾乎所有高階功能都是插件,統一的結果列舉如下:
enum PluginReceiveResult {
/// 插件已處理,不再交給使用者
RR_STOP_PROCESSING_AND_DEALLOCATE = 0,
/// 繼續交給其他插件,最後交給使用者
RR_CONTINUE_PROCESSING,
/// 插件要保留此訊息,不釋放也不再傳遞
RR_STOP_PROCESSING
};
enum PI2_LostConnectionReason {
LCR_CLOSED_BY_USER, // 呼叫 RakPeer::CloseConnection()
LCR_DISCONNECTION_NOTIFICATION, // 收到 ID_DISCONNECTION_NOTIFICATION
LCR_CONNECTION_LOST // 收到 ID_CONNECTION_LOST
};
enum PI2_FailedConnectionAttemptReason {
FCAR_CONNECTION_ATTEMPT_FAILED, FCAR_ALREADY_CONNECTED,
FCAR_NO_FREE_INCOMING_CONNECTIONS, FCAR_SECURITY_PUBLIC_KEY_MISMATCH,
FCAR_CONNECTION_BANNED, FCAR_INVALID_PASSWORD,
FCAR_INCOMPATIBLE_PROTOCOL, FCAR_IP_RECENTLY_CONNECTED,
FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY, FCAR_OUR_SYSTEM_REQUIRES_SECURITY,
FCAR_PUBLIC_KEY_MISMATCH
};
class RAK_DLL_EXPORT PluginInterface2 {
public:
PluginInterface2();
virtual ~PluginInterface2();
virtual void OnAttach(void) {} // 掛載
virtual void OnDetach(void) {} // 卸載
virtual void Update(void) {} // 週期更新
virtual PluginReceiveResult OnReceive(Packet *packet) // 每個封包都會經過
{ (void) packet; return RR_CONTINUE_PROCESSING; }
virtual void OnRakPeerStartup(void) {}
virtual void OnRakPeerShutdown(void) {}
virtual void OnClosedConnection(const SystemAddress &systemAddress,
RakNetGUID rakNetGuid, PI2_LostConnectionReason lostConnectionReason) {}
virtual void OnNewConnection(const SystemAddress &systemAddress,
RakNetGUID rakNetGuid, bool isIncoming) {}
virtual void OnFailedConnectionAttempt(Packet *packet,
PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) {}
/// 回傳 true 才會收到以下低階回呼;且此後不可再 Attach/Detach
virtual bool UsesReliabilityLayer(void) const { return false; }
virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed,
SystemAddress remoteSystemAddress) {}
virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed,
SystemAddress remoteSystemAddress) {}
virtual void OnReliabilityLayerNotification(const char *errorMessage,
const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError) {}
virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber,
SystemAddress remoteSystemAddress, RakNet::TimeMS time, int isSend) {}
virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress,
RakNet::TimeMS time) {}
virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed,
SystemAddress remoteSystemAddress) {}
RakNetGUID GetMyGUIDUnified(void) const;
protected:
// 統一發送介面,內部自動選擇 rakPeerInterface 或 tcpInterface
void SendUnified(const RakNet::BitStream *bitStream, PacketPriority priority,
PacketReliability reliability, char orderingChannel,
const AddressOrGUID systemIdentifier, bool broadcast);
Packet *AllocatePacketUnified(unsigned dataSize);
void PushBackPacketUnified(Packet *packet, bool pushAtHead);
void DeallocPacketUnified(Packet *packet);
RakPeerInterface *rakPeerInterface;
};
EmailSender 可直接用於伺服器端的通知郵件,介面簡潔:
class RAK_DLL_EXPORT EmailSender {
public:
STATIC_FACTORY_DECLARATIONS(EmailSender)
/// \return 成功回傳 0,否則回傳錯誤訊息字串
const char *Send(const char *hostAddress, unsigned short hostPort,
const char *sender, const char *recipient,
const char *senderName, const char *recipientName,
const char *subject, const char *body,
FileList *attachedFiles, bool doPrintf, const char *password);
protected:
const char *GetResponse(TCPInterface *tcpInterface,
const SystemAddress &emailServer, bool doPrintf);
RakNetRandom rakNetRandom;
};
支援附件與 SMTP 認證。若要走 TLS(例如 Gmail),需在 RakNetDefines.h 中定義 OPEN_SSL_CLIENT_SUPPORT,並注意 Gmail 使用 465 連接埠而非 25。
LogCommandParser 繼承 CommandParserInterface,提供執行期命令列的日誌操作能力:
class RAK_DLL_EXPORT LogCommandParser : public CommandParserInterface
MessageFilter 用於封包層級的存取控制,可設定白名單、超速封禁、逾時踢出等策略:
struct FilterSet {
bool banOnFilterTimeExceed;
bool kickOnDisallowedMessage;
bool banOnDisallowedMessage;
RakNet::TimeMS disallowedMessageBanTimeMS;
RakNet::TimeMS timeExceedBanTimeMS;
RakNet::TimeMS maxMemberTimeMS;
void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress,
int filterSetID, void *userData, unsigned char messageID);
void *disallowedCallbackUserData;
void (*timeoutCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress,
int filterSetID, void *userData);
void *timeoutUserData;
int filterSetID;
bool allowedIDs[MESSAGE_FILTER_MAX_MESSAGE_ID];
DataStructures::OrderedList<RakNet::RakString, RakNet::RakString> allowedRPC4;
};
struct FilteredSystem {
FilterSet *filter;
RakNet::TimeMS timeEnteredThisSet;
};
class RAK_DLL_EXPORT MessageFilter : public PluginInterface2
// 關鍵成員
DataStructures::OrderedList<int, FilterSet*, FilterSetComp> filterList;
DataStructures::Hash systemList;
單向認證是「客戶端把帳號密碼送給伺服器比對」;雙向認證則是互相驗證:客戶端先送出憑證,伺服器比對通過後,再把伺服器自己的憑證回傳給客戶端比對,雙方都通過才建立連線。
class RAK_DLL_EXPORT TwoWayAuthentication : public PluginInterface2
/// \internal
struct PendingChallenge {
RakNet::RakString identifier;
AddressOrGUID remoteSystem;
RakNet::Time time;
bool sentHash;
};
DataStructures::Queue<PendingChallenge> outgoingChallenges;
struct NonceAndRemoteSystemRequest {
char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH];
RakNet::AddressOrGUID remoteSystem;
unsigned short requestId;
RakNet::Time whenGenerated;
};
// 關鍵成員:key 為 identifier,data 為密碼
DataStructures::Hash<RakNet::RakString, RakNet::RakString, 16,
RakNet::RakString::ToInteger> passwords;
Nonce(一次性隨機數)機制可有效阻絕重放攻擊。
TransportInterface 抽象了「傳送與接收」的能力,讓 ConsoleServer 可以跑在 Telnet 或 RakNet 之上:
class RAK_DLL_EXPORT TransportInterface {
public:
virtual bool Start(unsigned short port, bool serverMode) = 0;
virtual void Stop(void) = 0;
virtual void Send(SystemAddress systemAddress, const char *data, ...) = 0;
virtual void CloseConnection(SystemAddress systemAddress) = 0;
/// 回傳一個封包,Packet::data / length / systemAddress 需填妥
virtual Packet* Receive(void) = 0;
virtual void DeallocatePacket(Packet *packet) = 0;
/// 有新連線進入時,把事件排入佇列並在此回傳其位址
virtual SystemAddress HasNewIncomingConnection(void) = 0;
virtual SystemAddress HasLostConnection(void) = 0;
/// 傳輸層若有可遠端修改的功能(如密碼、回顯),可自帶命令解析器
virtual CommandParserInterface* GetCommandParser(void) = 0;
};
enum NATTypeDetectionResult {
NAT_TYPE_NONE, // 可與任何人連線
NAT_TYPE_FULL_CONE, // 完整錐型
NAT_TYPE_ADDRESS_RESTRICTED, // 位址受限錐型
NAT_TYPE_PORT_RESTRICTED, // 連接埠受限錐型
NAT_TYPE_SYMMETRIC, // 對稱型,每次目標不同則連接埠不同
NAT_TYPE_UNKNOWN,
NAT_TYPE_DETECTION_IN_PROGRESS,
NAT_TYPE_SUPPORTS_UPNP,
NAT_TYPE_COUNT // \internal 必須是最後一項
};
對稱型 NAT 是穿透成功率最低的一種:因為每個外部目的地都會配置不同連接埠,第一次穿透必然失敗,必須依賴連接埠預測(MAX_PREDICTIVE_PORT_RANGE > 1)且路由器採用順序配置連接埠才有機會成功。
class RAK_DLL_EXPORT NatTypeDetectionClient : public PluginInterface2, public RNS2EventHandler {
STATIC_FACTORY_DECLARATIONS(NatTypeDetectionClient)
void DetectNATType(SystemAddress _serverAddress); // 向伺服器請求檢測
};
class RAK_DLL_EXPORT NatTypeDetectionServer : public PluginInterface2, public RNS2EventHandler {
STATIC_FACTORY_DECLARATIONS(NatTypeDetectionServer)
/// 啟動時需額外綁定 3 個未被占用的外部 IP
void Startup(const char *nonRakNetIP2, const char *nonRakNetIP3, const char *nonRakNetIP4);
void Shutdown(void);
protected:
enum NATDetectionState {
STATE_NONE, STATE_TESTING_NONE_1, STATE_TESTING_NONE_2,
STATE_TESTING_FULL_CONE_1, STATE_TESTING_FULL_CONE_2,
STATE_TESTING_ADDRESS_RESTRICTED_1, STATE_TESTING_ADDRESS_RESTRICTED_2,
STATE_TESTING_PORT_RESTRICTED_1, STATE_TESTING_PORT_RESTRICTED_2,
STATE_DONE,
};
struct NATDetectionAttempt {
SystemAddress systemAddress;
NATDetectionState detectionState;
RakNet::TimeMS nextStateTime;
RakNet::TimeMS timeBetweenAttempts;
unsigned short c2Port;
RakNetGUID guid;
};
RakNetSocket2 *s1p2, *s2p3, *s3p4, *s4p5;
};
struct RemoteClient {
RemoteClient() {
#if OPEN_SSL_CLIENT_SUPPORT == 1
ssl = 0;
#endif
isActive = false;
socket = 0;
}
__TCPSOCKET__ socket;
SystemAddress systemAddress;
DataStructures::ByteQueue outgoingData;
bool isActive;
SimpleMutex outgoingDataMutex, isActiveMutex;
#if OPEN_SSL_CLIENT_SUPPORT == 1
SSL* ssl;
bool InitSSL(SSL_CTX* ctx, SSL_METHOD *meth);
void DisconnectSSL(void);
void FreeSSL(void);
#endif
void SendOrBuffer(const char **data, const unsigned int *lengths, const int numParameters);
};
class RAK_DLL_EXPORT TCPInterface // 簡單的多執行緒 TCP 伺服器
enum RPCErrorCodes {
/// 函數未透過 RegisterFunction() 註冊,請檢查拼字
RPC_ERROR_FUNCTION_NOT_REGISTERED,
};
/// 在全域註冊函數:實際註冊會在 RPC4 掛載到 RakPeer 或 TCPInterface 時發生
class RAK_DLL_EXPORT RPC4GlobalRegistration {
public:
RPC4GlobalRegistration(const char* uniqueID,
void (*functionPointer)(RakNet::BitStream *userData, Packet *packet));
RPC4GlobalRegistration(const char* uniqueID,
void (*functionPointer)(RakNet::BitStream *userData, Packet *packet),
int callPriority);
/// 阻塞式函數,透過 returnData 回傳結果
RPC4GlobalRegistration(const char* uniqueID,
void (*functionPointer)(RakNet::BitStream *userData,
RakNet::BitStream *returnData, Packet *packet));
/// 以訊息 ID 註冊本地回呼
RPC4GlobalRegistration(const char* uniqueID, MessageID messageId);
};
class RAK_DLL_EXPORT RPC4 : public PluginInterface2
enum PatchContext {
PC_HASH_1_WITH_PATCH, // 含雜湊值
PC_HASH_2_WITH_PATCH,
PC_WRITE_FILE, // 直接寫入檔案
PC_ERROR_FILE_WRITE_FAILURE, // 寫檔失敗
PC_ERROR_PATCH_TARGET_MISSING, // 目標檔案缺失
PC_ERROR_PATCH_APPLICATION_FAILURE, // 套用補丁失敗
PC_ERROR_PATCH_RESULT_CHECKSUM_FAILURE, // 結果校驗失敗
PC_NOTICE_WILL_COPY_ON_RESTART, // 通知將於重啟後複製
PC_NOTICE_FILE_DOWNLOADED, // 通知檔案已下載
PC_NOTICE_FILE_DOWNLOADED_PATCH // 通知補丁已下載
};
更新流程的關鍵在於增量下載:伺服器只回傳自上次同步日期後新增、修改與刪除的檔案清單,客戶端比對雜湊後,只下載有差異的部分,多數情況連整檔都不必傳,只傳 binary patch。
class AutopatcherRepositoryInterface : public IncrementalReadInterface {
public:
/// 取得自某日期後的變更清單
virtual bool GetChangelistSinceDate(const char *applicationName,
FileList *addedOrModifiedFilesWithHashData, FileList *deletedFiles,
double sinceDate) = 0;
/// 取得補丁。回傳 1 成功,0 資料庫失敗,-1 需下載原始檔
virtual int GetPatches(const char *applicationName, FileList *input,
bool allowDownloadOfOriginalUnmodifiedFiles, FileList *patchList) = 0;
/// 取得最近一次更新的完整內容(補丁 + 新檔 + 雜湊 + 刪除清單)
virtual bool GetMostRecentChangelistWithPatches(
RakNet::RakString &applicationName, FileList *patchedFiles,
FileList *updatedFiles, FileList *addedOrModifiedFileHashes,
FileList *deletedFiles, double *priorRowPatchTime,
double *mostRecentRowPatchTime) = 0;
virtual const char *GetLastError(void) const = 0;
virtual const int GetIncrementalReadChunkSize(void) const = 0;
};
Router2 讓兩個無法直接連線的系統,透過一個雙方都連著的中間節點轉發封包。
enum Router2RequestStates {
R2RS_REQUEST_STATE_QUERY_FORWARDING,
REQUEST_STATE_REQUEST_FORWARDING,
};
struct ConnectionRequestSystem {
RakNetGUID guid;
int pingToEndpoint;
unsigned short usedForwardingEntries;
};
struct ConnnectRequest {
DataStructures::List<ConnectionRequestSystem> connectionRequestSystems;
SimpleMutex connectionRequestSystemsMutex;
Router2RequestStates requestState;
RakNet::TimeMS pingTimeout;
RakNetGUID endpointGuid;
RakNetGUID lastRequestedForwardingSystem;
bool returnConnectionLostOnFailure;
};
struct MiniPunchRequest {
RakNetGUID endpointGuid;
SystemAddress endpointAddress;
bool gotReplyFromEndpoint;
RakNetGUID sourceGuid;
SystemAddress sourceAddress;
bool gotReplyFromSource;
RakNet::TimeMS timeout, nextAction;
unsigned short forwardingPort;
__UDPSOCKET__ forwardingSocket;
};
struct ForwardedConnection {
RakNetGUID endpointGuid;
RakNetGUID intermediaryGuid;
SystemAddress intermediaryAddress;
bool returnConnectionLostOnFailure;
bool weInitiatedForwarding;
};
class RAK_DLL_EXPORT Router2 : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(Router2)
void SetSocketFamily(unsigned short _socketFamily);
/// \note 請一律使用 RakNetGuid 而非 SystemAddress 識別連線,
/// 位址可能變動,變動時會收到 ID_ROUTER_2_REROUTED
void EstablishRouting(RakNetGUID endpointGuid);
void SetMaximumForwardingRequests(int max); // 預設 0
void SetDebugInterface(Router2DebugInterface *_debugInterface);
};
RelayPlugin 讓系統以「字串名稱」而非 GUID 被識別,並內建聊天室(群組)概念:
enum RelayPluginEnums {
// 伺服器處理
RPE_MESSAGE_TO_SERVER_FROM_CLIENT,
RPE_ADD_CLIENT_REQUEST_FROM_CLIENT,
RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT,
RPE_GROUP_MESSAGE_FROM_CLIENT,
RPE_JOIN_GROUP_REQUEST_FROM_CLIENT,
RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT,
RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT,
// 客戶端處理
RPE_MESSAGE_TO_CLIENT_FROM_SERVER,
RPE_ADD_CLIENT_NOT_ALLOWED,
RPE_ADD_CLIENT_TARGET_NOT_CONNECTED,
RPE_ADD_CLIENT_NAME_ALREADY_IN_USE,
RPE_ADD_CLIENT_SUCCESS,
RPE_USER_ENTERED_ROOM,
RPE_USER_LEFT_ROOM,
RPE_GROUP_MSG_FROM_SERVER,
RPE_GET_GROUP_LIST_REPLY_FROM_SERVER,
RPE_JOIN_GROUP_SUCCESS,
RPE_JOIN_GROUP_FAILURE,
};
struct StrAndGuidAndRoom { RakString str; RakNetGUID guid; RakString currentRoom; };
struct RP_Group { RakString roomName; DataStructures::List<StrAndGuid> usersInRoom; };
class RAK_DLL_EXPORT RelayPlugin : public PluginInterface2
// 關鍵成員
DataStructures::Hash<RakString, StrAndGuidAndRoom*, 8096, RakNet::RakString::ToInteger> strToGuidHash;
DataStructures::Hash<RakNetGUID, StrAndGuidAndRoom*, 8096, RakNet::RakNetGUID::ToUint32> guidToStrHash;
DataStructures::List<RP_Group*> chatRooms;
bool acceptAddParticipantRequests;
FileListTransfer 提供檔案集合的傳輸能力,透過回呼介面讓使用者掌握進度:
class FileListTransferCBInterface {
public:
struct OnFileStruct {
unsigned fileIndex; // 0 ~ numberOfFilesInThisSet
char fileName[512];
char *fileData;
BitSize_t byteLengthOfThisFile;
BitSize_t bytesDownloadedForThisFile;
unsigned short setID; // SetupReceive 回傳的集合識別
unsigned numberOfFilesInThisSet;
unsigned byteLengthOfThisSet; // 未壓縮的總長
unsigned bytesDownloadedForThisSet;
FileListNodeContext context;
SystemAddress senderSystemAddress;
RakNetGUID senderGuid; // 僅 RakPeer(UDP) 有效
};
struct FileProgressStruct {
OnFileStruct *onFileStruct;
unsigned int partCount; // 完成百分比 = 100 * (partCount+1)/partTotal
unsigned int partTotal; // 每片約為 MTU 減去 UDP 與 RakNet 標頭
unsigned int dataChunkLength;
char *firstDataChunk; // 檔案開頭,可在下載途中讀取識別資訊
char *iriDataChunk; // 增量讀取的區塊,回呼後即失效
unsigned int iriWriteOffset;
SystemAddress senderSystemAddress;
RakNetGUID senderGuid;
bool allocateIrIDataChunkAutomatically; // 預設 true
};
struct DownloadCompleteStruct {
unsigned short setID;
unsigned numberOfFilesInThisSet;
unsigned byteLengthOfThisSet;
SystemAddress senderSystemAddress;
RakNetGUID senderGuid;
};
/// 回傳 true 表示讓 RakNet 釋放該檔的記憶體
virtual bool OnFile(OnFileStruct *onFileStruct) = 0;
virtual void OnFileProgress(FileProgressStruct *fps) = 0;
virtual bool Update(void) { return true; }
virtual bool OnDownloadComplete(DownloadCompleteStruct *dcs) { (void) dcs; return false; }
virtual void OnDereference(void) {}
};
class RAK_DLL_EXPORT FileListTransfer : public PluginInterface2
大檔傳輸時,若不希望整檔佔用記憶體,可搭配 IncrementalReadInterface 並把 allocateIrIDataChunkAutomatically 設為 false,在 OnFileProgress 中直接把區塊寫檔。
class RAK_DLL_EXPORT ConsoleServer {
public:
STATIC_FACTORY_DECLARATIONS(ConsoleServer)
/// Telnet 預設使用連接埠 23,RakNet 則可自訂
void SetTransportProvider(TransportInterface *transportInterface, unsigned short port);
void AddCommandParser(CommandParserInterface *commandParserInterface);
void RemoveCommandParser(CommandParserInterface *commandParserInterface);
void Update(void); // 需頻繁呼叫以讀取傳輸層封包
void SetPrompt(const char *_prompt); // 傳空字串可清除提示符
protected:
TransportInterface *transport;
DataStructures::List<CommandParserInterface *> commandParserList;
};
維護整張 P2P 網路的拓撲,可查詢任意兩節點是否相連、平均延遲,並找出延遲最低的節點作為資料中繼:
class RAK_DLL_EXPORT ConnectionGraph2 : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(ConnectionGraph2)
bool GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid,
SystemAddress *saOut, RakNetGUID *guidOut, unsigned int *outLength);
bool ConnectionExists(RakNetGUID g1, RakNetGUID g2);
uint16_t GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) const; // 無連線回傳 -1
/// 回傳所有連線中平均延遲最低的系統,適合在主持人遷移後挑選中繼節點
RakNetGUID GetLowestAveragePingSystem(void) const;
/// 設為 false 時,新連線不會自動加入拓撲,需手動呼叫 AddParticipant()
void SetAutoProcessNewConnections(bool b);
bool GetAutoProcessNewConnections(void) const;
void AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGuid);
void GetParticipantList(DataStructures::OrderedList<RakNetGUID, RakNetGUID> &participantList);
};
雲端是一套分散式的鍵值資料儲存:客戶端上傳資料,其他客戶端可依鍵查詢並訂閱更新。伺服器端與客戶端各自實作。
struct RAK_DLL_EXPORT CloudKey {
CloudKey() {}
CloudKey(RakNet::RakString _primaryKey, uint32_t _secondaryKey)
: primaryKey(_primaryKey), secondaryKey(_secondaryKey) {}
/// 主要類別,例如應用名稱,不可為空
RakNet::RakString primaryKey;
/// 子類別列舉,例如 PLAYER_LIST 或 RUNNING_SCORES
uint32_t secondaryKey;
};
struct RAK_DLL_EXPORT CloudQuery {
CloudQuery() { startingRowIndex = 0; maxRowsToReturn = 0; subscribeToResults = false; }
DataStructures::List<CloudKey> keys; // 至少 1 個
uint32_t startingRowIndex; // 僅在 maxRowsToReturn > 0 時有效
uint32_t maxRowsToReturn; // 0 表示不限制
bool subscribeToResults; // 自動接收結果變更通知
};
struct RAK_DLL_EXPORT CloudQueryRow {
CloudKey key;
unsigned char *data;
uint32_t length;
SystemAddress serverSystemAddress; // 持有此資料的伺服器
SystemAddress clientSystemAddress; // 上傳此資料的客戶端
RakNetGUID serverGUID;
RakNetGUID clientGUID;
};
struct RAK_DLL_EXPORT CloudQueryResult {
CloudQuery cloudQuery;
DataStructures::List<CloudQueryRow*> rowsReturned;
/// 多鍵查詢時,各鍵結果的起始索引,例如 4 個鍵回傳 3/0/5/12 筆 → 0,3,3,8
DataStructures::List<uint32_t> resultKeyIndices;
bool subscribeToResults;
};
class RAK_DLL_EXPORT CloudClientCallback {
public:
virtual void OnGet(RakNet::CloudQueryResult *result, bool *deallocateRowsAfterReturn) {}
/// wasUpdated 為 true 表示更新,false 表示刪除(result 為刪除前的最後值)
virtual void OnSubscriptionNotification(RakNet::CloudQueryRow *result,
bool wasUpdated, bool *deallocateRowAfterReturn) {}
};
class RAK_DLL_EXPORT CloudServerQueryFilter {
public:
/// 回傳 false 即拒絕該請求;OnGetRequest 回傳 false 時客戶端不會收到任何回應
virtual bool OnPostRequest(RakNetGUID clientGuid, SystemAddress clientAddress,
CloudKey key, uint32_t dataLength, const char *data) = 0;
virtual bool OnReleaseRequest(RakNetGUID clientGuid, SystemAddress clientAddress,
DataStructures::List<CloudKey> &cloudKeys) = 0;
virtual bool OnGetRequest(RakNetGUID clientGuid, SystemAddress clientAddress,
CloudQuery &query, DataStructures::List<RakNetGUID> &specificSystems) = 0;
virtual bool OnUnsubscribeRequest(RakNetGUID clientGuid, SystemAddress clientAddress,
DataStructures::List<CloudKey> &cloudKeys,
DataStructures::List<RakNetGUID> &specificSystems) = 0;
};
class RAK_DLL_EXPORT CloudClient : public PluginInterface2
class RAK_DLL_EXPORT CloudServer : public PluginInterface2, CloudAllocator
用於物件狀態的網路同步(建立、銷毀、序列化、可見性變更),透過位元標誌控制哪些回呼被啟用:
enum {
REPLICA_RECEIVE_DESTRUCTION = 1 << 0,
REPLICA_RECEIVE_SERIALIZE = 1 << 1,
REPLICA_RECEIVE_SCOPE_CHANGE = 1 << 2,
REPLICA_SEND_CONSTRUCTION = 1 << 3,
REPLICA_SEND_DESTRUCTION = 1 << 4,
REPLICA_SEND_SCOPE_CHANGE = 1 << 5,
REPLICA_SEND_SERIALIZE = 1 << 6,
REPLICA_SET_ALL = 0xFF
};
enum ReplicaReturnResult {
REPLICA_PROCESS_LATER, // 稍後再以相同參數呼叫
REPLICA_PROCESSING_DONE, // 正常完成
REPLICA_CANCEL_PROCESS, // 取消,不發送訊息也不改變狀態
REPLICA_PROCESS_AGAIN, // 已發送但不清除 send bit,適合不同可靠性的分段傳送
REPLICA_PROCESS_IMPLICIT // 僅用於 SendConstruction:視為對方已有此物件
};
class RAK_DLL_EXPORT ReplicaManager3 : public PluginInterface2
class RAK_DLL_EXPORT Connection_RM3
class RAK_DLL_EXPORT Replica3 : public NetworkIDObject
template <class parent_type>
class RAK_DLL_EXPORT Replica3Composite : public Replica3
維護一個「每個節點都互相認識」的 mesh,並在節點加入/離開時自動同步拓撲資訊。
/// \internal
struct FCM2Participant {
FCM2Participant() {}
FCM2Participant(const FCM2Guid &_fcm2Guid, const RakNetGUID &_rakNetGuid)
: fcm2Guid(_fcm2Guid), rakNetGuid(_rakNetGuid) {}
// 低半部為隨機數,高半部為連線順序(totalConnectionCount)
FCM2Guid fcm2Guid;
RakNetGUID rakNetGuid;
};
enum JoinInProgressState {
JIPS_PROCESSING, JIPS_FAILED, JIPS_CONNECTED, JIPS_UNNECESSARY,
};
struct VerifiedJoinInProgressMember {
SystemAddress systemAddress;
RakNetGUID guid;
JoinInProgressState joinInProgressState;
BitStream *userData;
bool workingFlag;
};
class RAK_DLL_EXPORT FullyConnectedMesh2 : public PluginInterface2
其 guid 分配流程值得一看:啟動時 ourFCMGuid 為 unknown,透過比較雙方啟動時間決定誰來生成全域 guid,再以 totalConnectionCount 作為高位計數,確保網路中 guid 唯一且順序一致。
提供兩種封裝:HTTPConnection(直接包裝 TCP)與 HTTPConnection2(以插件形式實作)。
class RAK_DLL_EXPORT HTTPConnection {
public:
STATIC_FACTORY_DECLARATIONS(HTTPConnection)
/// \pre tcp 必須已 Start()
void Init(TCPInterface *_tcp, const char *host, unsigned short port = 80);
/// \pre IsBusy() == false(HTTP 每條連線同時僅允許一個請求)
void Post(const char *path, const char *data,
const char *_contentType = "application/x-www-form-urlencoded");
void Get(const char *path);
bool HasRead(void) const;
RakNet::RakString Read(void);
void Update(void);
SystemAddress GetServerAddress(void) const;
void ProcessTCPPacket(Packet *packet); // 取完所有資料後回傳 true
enum ResponseCodes { NoBody = 1001, OK = 200, Deleted = 1002 };
struct BadResponse {
BadResponse() { code = 0; }
operator int () const { return code; }
RakNet::RakString data;
int code;
};
bool HasBadResponse(int *code, RakNet::RakString *data);
bool IsBusy(void) const;
};
class RAK_DLL_EXPORT HTTPConnection2 : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(HTTPConnection2)
/// 字串可用 RakString::FormatForPOST() / FormatForGET() / FormatForDELETE() 產生
bool TransmitRequest(const char* stringToTransmit, const char* host,
unsigned short port = 80, bool useSSL = false, int ipVersion = 4,
SystemAddress useAddress = UNASSIGNED_SYSTEM_ADDRESS, void *userData = 0);
/// TCP 是串流式的,回應可能需多次 Receive() 才收齊;
/// contentOffset 等同於在回應中搜尋 \r\n\r\n 的位置
bool GetResponse(RakString &stringTransmitted, RakString &hostTransmitted,
RakString &responseReceived, SystemAddress &hostReceived,
int &contentOffset, void **userData);
bool IsBusy(void) const;
bool HasResponse(void) const;
struct Request {
RakString stringToTransmit, stringReceived, host;
SystemAddress hostEstimatedAddress, hostCompletedAddress;
unsigned short port;
bool useSSL;
int contentOffset, contentLength, ipVersion;
void *userData;
bool chunked;
size_t thisChunkSize, bytesReadForThisChunk;
};
};
HTTPConnection2 另外處理了 chunked 編碼,這是自製 HTTP 客戶端時最容易被忽略的一塊。
struct TeamMember {
RakNetGUID memberGuid;
NetworkID memberId;
TeamId currentTeam;
TeamId requestedTeam;
};
enum JoinTeamType {
JOIN_ANY_AVAILABLE_TEAM, // 加入第一個有空位的隊伍
JOIN_SPECIFIC_TEAM, // 加入指定隊伍
JOIN_NO_TEAM // 不加入任何隊伍,必定成功
};
enum TMTopology {
TM_PEER_TO_PEER, // 每個系統把訊息送給所有參與者
TM_CLIENT_SERVER, // 由主持人轉發給所有參與者
};
struct TeamSelection {
JoinTeamType joinTeamType;
union { TM_Team *specificTeamToJoin; NoTeamId noTeamSubcategory; } teamParameter;
static TeamSelection AnyAvailable(void);
static TeamSelection SpecificTeam(TM_Team *specificTeamToJoin);
/// 不加入隊伍時仍可標記子類別,例如 AI 或旁觀者
static TeamSelection NoTeam(NoTeamId noTeamSubcategory);
};
class RAK_DLL_EXPORT TM_TeamMember // 包含資料與操作(管理隊伍、隊員)
class RAK_DLL_EXPORT TM_Team // 一個隊伍
class TM_World // 存放隊伍列表,負責平衡
class RAK_DLL_EXPORT TeamManager : public PluginInterface2 // 自動化網路與隊伍列表管理
UDPProxy 由協調者(Coordinator)、伺服器(Server)、客戶端(Client)三方組成,用來在雙方 NAT 類型都過於嚴格時提供一台上報的轉發節點。
enum UDPProxyMessages {
ID_UDP_PROXY_FORWARDING_SUCCEEDED,
ID_UDP_PROXY_FORWARDING_NOTIFICATION,
ID_UDP_PROXY_NO_SERVERS_ONLINE,
ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR,
ID_UDP_PROXY_ALL_SERVERS_BUSY,
ID_UDP_PROXY_IN_PROGRESS,
ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR,
ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT,
ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR,
ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER,
ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR,
ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR,
ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER,
ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER,
ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER,
ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER
};
class RAK_DLL_EXPORT UDPProxyCoordinator : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(UDPProxyCoordinator)
/// 未設定密碼時,伺服器無法遠端登入(預設無密碼)
void SetRemoteLoginPassword(RakNet::RakString password);
struct SenderAndTargetAddress {
SystemAddress senderClientAddress;
RakNetGUID senderClientGuid;
SystemAddress targetClientAddress;
RakNetGUID targetClientGuid;
};
struct ServerWithPing { unsigned short ping; SystemAddress serverAddress; };
};
struct UDPProxyClientResultHandler {
virtual void OnForwardingSuccess(const char *proxyIPAddress, unsigned short proxyPort,
SystemAddress proxyCoordinator, SystemAddress sourceAddress,
SystemAddress targetAddress, RakNetGUID targetGuid,
RakNet::UDPProxyClient *proxyClientPlugin) = 0;
virtual void OnForwardingNotification(...); // 他人以我方為目標建立轉發
virtual void OnNoServersOnline(...);
virtual void OnRecipientNotConnected(...);
virtual void OnAllServersBusy(...); // 可增加伺服器或提高轉發上限
virtual void OnForwardingInProgress(...); // 重複請求,可忽略
};
class RAK_DLL_EXPORT UDPProxyClient : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(UDPProxyClient)
void SetResultHandler(UDPProxyClientResultHandler *rh);
bool RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress,
SystemAddress targetAddressAsSeenFromCoordinator,
RakNet::TimeMS timeoutOnNoDataMS,
RakNet::BitStream *serverSelectionBitstream = 0);
/// 另一版本以 GUID 指定目標,省去查 IP 的麻煩
bool RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress,
RakNetGUID targetGuid, RakNet::TimeMS timeoutOnNoDataMS,
RakNet::BitStream *serverSelectionBitstream = 0);
};
class RAK_DLL_EXPORT UDPProxyServer : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(UDPProxyServer)
void SetSocketFamily(unsigned short _socketFamily);
bool LoginToCoordinator(RakNet::RakString password, SystemAddress coordinatorAddress);
/// 若伺服器與協調者在同一 LAN,回報給客戶端的會是內部位址,
/// 此時必須呼叫 SetServerPublicIP() 告訴客戶端該連哪個位址
void SetServerPublicIP(RakString ip);
UDPForwarder udpForwarder; // 實際執行轉發的類別
};
timeoutOnNoDataMS 的選值有個實務依據:RakNet 協定保證至少每 5 秒發送一次訊息,因此轉發 RakNet 封包時取 5 秒再加上幾秒延遲餘裕是合理值;官方建議一般情境用 10 秒。
struct RAK_DLL_EXPORT PunchthroughConfiguration {
/// 內部:(15ms * 2 tries + 30 wait) * 5 ports * 8 players = 2.4 秒
/// 外部:(50ms * 8 sends + 200 wait) * 2 ports * 8 players = 9.6 秒
/// 合計約 8 秒
PunchthroughConfiguration() {
TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL = 15;
TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL = 50;
UDP_SENDS_PER_PORT_INTERNAL = 2;
UDP_SENDS_PER_PORT_EXTERNAL = 8;
INTERNAL_IP_WAIT_AFTER_ATTEMPTS = 30;
MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK = 5; // 設為 0 可停用 LAN 直連
MAX_PREDICTIVE_PORT_RANGE = 2;
EXTERNAL_IP_WAIT_BETWEEN_PORTS = 200;
EXTERNAL_IP_WAIT_AFTER_FIRST_TTL = 100;
EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS = EXTERNAL_IP_WAIT_BETWEEN_PORTS;
retryOnFailure = false;
}
RakNet::Time TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL, TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL;
int UDP_SENDS_PER_PORT_INTERNAL, UDP_SENDS_PER_PORT_EXTERNAL;
int INTERNAL_IP_WAIT_AFTER_ATTEMPTS;
int MAX_PREDICTIVE_PORT_RANGE; // 已知起始埠之後要嘗試的外部埠數
int EXTERNAL_IP_WAIT_AFTER_FIRST_TTL, EXTERNAL_IP_WAIT_BETWEEN_PORTS;
int EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS;
int MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK;
/// 首次失敗後再試一次;因為對端路由器可能在回應前正等待更高編號的埠
bool retryOnFailure;
};
class RAK_DLL_EXPORT NatPunchthroughClient : public PluginInterface2
class RAK_DLL_EXPORT NatPunchthroughServer : public PluginInterface2 {
public:
STATIC_FACTORY_DECLARATIONS(NatPunchthroughServer)
void SetDebugInterface(NatPunchthroughServerDebugInterface *i);
struct User {
RakNetGUID guid;
SystemAddress systemAddress;
unsigned short mostRecentPort;
bool isReady; // ready 表示可進行穿透
DataStructures::OrderedList<RakNetGUID, RakNetGUID> groupPunchthroughRequests;
DataStructures::List<ConnectionAttempt *> connectionAttempts;
};
struct ConnectionAttempt {
User *sender, *recipient;
uint16_t sessionId;
RakNet::Time startTime;
enum { NAT_ATTEMPT_PHASE_NOT_STARTED, NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS }
attemptPhase;
};
protected:
SystemAddress boundAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS];
unsigned char boundAddressCount;
};
enum DynDnsResultCode {
// ----- 成功 -----
RC_SUCCESS,
RC_DNS_ALREADY_SET, // 無需動作
// ----- 可忽略的失敗(視同成功) -----
RC_NO_CHANGE,
// ----- 使用者錯誤 -----
RC_NOT_DONATOR, // 需付費
RC_NO_HOST, // 主機不存在
RC_BAD_AUTH, // 密碼錯誤
RC_NOT_YOURS, // 非本人主機
// ----- 永久性失敗 -----
RC_ABUSE, RC_TCP_FAILED_TO_START, RC_TCP_DID_NOT_CONNECT,
RC_UNKNOWN_RESULT, RC_PARSING_FAILURE,
RC_CONNECTION_LOST_WITHOUT_RESPONSE, RC_BAD_AGENT, RC_BAD_SYS,
RC_DNS_ERROR, RC_NOT_FQDN, RC_NUM_HOST, RC_911, RC_DYNDNS_TIMEOUT
};
class RAK_DLL_EXPORT DynDNS {
public:
// newIPAddress 傳 0 會自動偵測;usernameAndPassword 格式為 username:password
void UpdateHostIPAsynch(const char *dnsHost, const char *newIPAddress,
const char *usernameAndPassword);
void Update(void);
bool IsRunning(void) const { return connectPhase != CP_IDLE; }
bool IsCompleted(void) const { return connectPhase == CP_IDLE; }
RakNet::DynDnsResultCode GetCompletedResultCode(void) { return result; }
bool WasResultSuccessful(void) const {
return result == RC_SUCCESS || result == RC_DNS_ALREADY_SET || result == RC_NO_CHANGE;
}
char *GetMyPublicIP(void) const { return (char*) myIPStr; } // 流程中順帶取得
protected:
enum ConnectPhase {
CP_CONNECTING_TO_CHECKIP, CP_WAITING_FOR_CHECKIP_RESPONSE,
CP_CONNECTING_TO_DYNDNS, CP_WAITING_FOR_DYNDNS_RESPONSE, CP_IDLE
};
};
樣板類別,內建 Dijkstra 最短路徑與最小生成樹:
template <class node_type, class weight_type, bool allow_unlinkedNodes>
class RAK_DLL_EXPORT WeightedGraph {
public:
WeightedGraph();
WeightedGraph(const WeightedGraph& original_copy);
WeightedGraph& operator= (const WeightedGraph& original_copy);
void AddNode(const node_type &node);
void RemoveNode(const node_type &node);
void AddConnection(const node_type &node1, const node_type &node2, weight_type weight);
void RemoveConnection(const node_type &node1, const node_type &node2);
bool HasConnection(const node_type &node1, const node_type &node2);
bool GetShortestPath(DataStructures::List<node_type> &path,
node_type startNode, node_type endNode, weight_type INFINITE_WEIGHT);
bool GetSpanningTree(DataStructures::Tree<node_type> &outTree,
DataStructures::List<node_type> *inputNodes,
node_type startNode, weight_type INFINITE_WEIGHT);
unsigned GetNodeCount(void) const;
unsigned GetConnectionCount(unsigned nodeIndex) const;
void GetConnectionAtIndex(unsigned nodeIndex, unsigned connectionIndex,
node_type &outNode, weight_type &outWeight) const;
protected:
void GenerateDisjktraMatrix(node_type startNode, weight_type INFINITE_WEIGHT);
// 以 Map 實作的鄰接串列
DataStructures::Map<node_type, DataStructures::Map<node_type, weight_type> *> adjacencyLists;
struct NodeAndParent {
DataStructures::Tree<node_type> *node;
DataStructures::Tree<node_type> *parent;
};
};
RakPeer 是 RakPeerInterface 的實作,同時繼承 RNS2EventHandler。介面依職責可歸為幾組:
· 生命週期:Startup / Shutdown / IsActive
· 連線管理:Connect / ConnectWithSocket / CloseConnection / CancelConnectionAttempt / GetConnectionList / GetConnectionState
· 資料收發:Send(字串與 BitStream 兩版)/ SendList / Receive / DeallocatePacket / AllocatePacket / SendOutOfBand
· 安全性:InitializeSecurity / DisableSecurity / 例外清單管理
· 延遲與統計:Ping / GetAveragePing / GetLastPing / GetLowestPing / GetStatistics
· 位址與識別:GetInternalID / GetExternalID / GetMyGUID / GetSystemAddressFromGuid
· 封禁與頻率:AddToBanList / IsBanned / SetLimitIPConnectionFrequency
· 插件:AttachPlugin / DetachPlugin
· 模擬:ApplyNetworkSimulator(丟包率、額外延遲),以及 SetPerConnectionOutgoingBandwidthLimit
class RAK_DLL_EXPORT RakPeer : public RakPeerInterface, public RNS2EventHandler {
public:
StartupResult Startup(unsigned int maxConnections, SocketDescriptor *socketDescriptors,
unsigned socketDescriptorCount, int threadPriority = -99999);
bool InitializeSecurity(const char *publicKey, const char *privateKey,
bool bRequireClientKey = false);
ConnectionAttemptResult Connect(const char* host, unsigned short remotePort,
const char *passwordData, int passwordDataLength, PublicKey *publicKey = 0,
unsigned connectionSocketIndex = 0, unsigned sendConnectionAttemptCount = 6,
unsigned timeBetweenSendConnectionAttemptsMS = 1000,
RakNet::TimeMS timeoutTime = 0);
uint32_t Send(const RakNet::BitStream *bitStream, PacketPriority priority,
PacketReliability reliability, char orderingChannel,
const AddressOrGUID systemIdentifier, bool broadcast,
uint32_t forceReceiptNumber = 0);
Packet* Receive(void);
void DeallocatePacket(Packet *packet);
void AttachPlugin(PluginInterface2 *plugin);
void DetachPlugin(PluginInterface2 *messageHandler);
/// \internal 已連線系統的所有資訊
struct RemoteSystemStruct {
bool isActive;
SystemAddress systemAddress; // 對方的外部 IP
SystemAddress myExternalSystemAddress; // 對方眼中我的外部 IP
SystemAddress theirInternalSystemAddress[MAXIMUM_NUMBER_OF_INTERNAL_IDS];
ReliabilityLayer reliabilityLayer; // 該玩家的可靠性層
bool weInitiatedTheConnection;
PingAndClockDifferential pingAndClockDifferential[PING_TIMES_ARRAY_SIZE];
unsigned short lowestPing;
RakNet::Time nextPingTime;
RakNet::Time lastReliableSend; // 可靠資料至少每 timeoutTime/2 送一次以偵測斷線
RakNet::Time connectionTime;
RakNetGUID guid;
int MTUSize;
RakNetSocket2* rakNetSocket;
enum ConnectMode {
NO_ACTION, DISCONNECT_ASAP, DISCONNECT_ASAP_SILENTLY, DISCONNECT_ON_NO_ACK,
REQUESTED_CONNECTION, HANDLING_CONNECTION_REQUEST,
UNVERIFIED_SENDER, CONNECTED
} connectMode;
};
};
這裡有兩個設計細節值得注意:其一,remoteSystemList 在啟動時就預配置,執行期只移動指標而不配置/釋放記憶體,因此即使可靠性層正在執行也能安全增刪玩家;其二,使用者端的送訊息會先進入 bufferedCommands 佇列,由網路執行緒統一處理,避免多執行緒對位址結構的競爭。
讀完這一圈會發現,RakNet 真正強大的地方不在程式碼量,而在它的分層與插件化設計:
· 底層是 BitStream 與 ReliabilityLayer,負責位元級編碼與可靠傳輸;
· 中間是 RakPeer,管理連線、封包與執行緒;
· 上層則是幾十個彼此獨立的插件——穿透、代理、路由、雲端、副本、補丁、聊天室——需要的時候掛上去,不需要的時候完全不佔成本。
理解這個骨架之後,要為自己的遊戲補上一個自訂功能,只需要實作 PluginInterface2 再 AttachPlugin 即可,不必去動核心。
Android 用 Canvas 實現 ImageView 的陰影與圖層效果
本文分享一段以 Canvas 繪製 ImageView 陰影與圖層疊加效果的實作程式碼,供需要的朋友參考。 import android.app.Activity;
Struts2 開發 Action 的三種方式與通配符、常量詳解
在 Struts2 中,Action 是處理業務請求的核心。開發 Action 主要有三種方式,靈活度依次遞增。 方式一:繼承 ActionSupport 繼承 Acti
用 Cocos2d-x 實作 Android Toast 風格的浮動提示
Android 原生的 Toast 有個討人喜歡的特質:淡入、停留、淡出,然後自己消失,完全不打斷操作。用 Cocos2d-x 做手機遊戲時,也想有同樣的效果,於是就自己
Android 學習筆記:Home Screen Widgets(一)Widget 入門全解
什麼是 Home Screen Widgets Home Screen Widget,中文常譯作「小工具」或「桌面組件」,是掛在主畫面上的 View,其資料由後台進程定期