Added the udplibrary library

This commit is contained in:
Anonymous
2014-01-14 06:47:08 -07:00
parent f886210f4f
commit c55243bd19
17 changed files with 9528 additions and 0 deletions

2
external/3rd/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,2 @@
add_subdirectory(library)

2
external/3rd/library/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,2 @@
add_subdirectory(udplibrary)

View File

@@ -0,0 +1,21 @@
cmake_minimum_required(VERSION 2.8)
project(udplibrary)
if(WIN32)
add_definitions(/D_CRT_SECURE_NO_WARNINGS)
endif()
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
add_library(udplibrary
hashtable.hpp
PointerDeque.hpp
priority.hpp
UdpHandler.hpp
UdpHandler.h
UdpLibrary.cpp
UdpLibrary.hpp
UdpLibrary.h
)

View File

@@ -0,0 +1,126 @@
#ifndef POINTERDEQUE_HPP
#define POINTERDEQUE_HPP
// This is a simple double ended queue template. Any pointer-type can be stored in this deque
// I pop/peek return NULL if the queue is empty.
template<typename T> class PointerDeque
{
public:
PointerDeque(int entriesPerPage);
~PointerDeque();
void PushLeft(T* obj);
T* PopLeft();
void PushRight(T* obj);
T* PopRight();
T* PeekLeft();
T* PeekRight();
T* Peek(int index);
int Count();
protected:
void Expand();
int mEntriesPerPage;
T** mEntries;
int mEntriesCount;
int mEntriesMax;
int mOffsetLeft;
};
template<typename T> PointerDeque<T>::PointerDeque(int entriesPerPage)
{
mEntriesPerPage = entriesPerPage;
mEntries = NULL;
mOffsetLeft = 0;
mEntriesMax = 0;
mEntriesCount = 0;
}
template<typename T> PointerDeque<T>::~PointerDeque()
{
delete[] mEntries;
}
template<typename T> void PointerDeque<T>::Expand()
{
int countToEnd = (mEntriesMax - mOffsetLeft);
mEntriesMax += mEntriesPerPage;
T** newHold = new T*[mEntriesMax];
if (countToEnd < mEntriesCount)
{
memcpy(newHold, &mEntries[mOffsetLeft], countToEnd * sizeof(T*));
memcpy(newHold + countToEnd, mEntries, (mEntriesCount - countToEnd) * sizeof(T*));
}
else
memcpy(newHold, &mEntries[mOffsetLeft], mEntriesCount * sizeof(T*));
delete[] mEntries;
mEntries = newHold;
mOffsetLeft = 0;
}
template<typename T> void PointerDeque<T>::PushLeft(T* obj)
{
if (mEntriesCount >= mEntriesMax)
Expand();
mEntries[(mOffsetLeft - 1 + mEntriesMax) % mEntriesMax] = obj;
mEntriesCount++;
}
template<typename T> T* PointerDeque<T>::PopLeft()
{
if (mEntriesCount == 0)
return(NULL);
T* hold = mEntries[mOffsetLeft];
mOffsetLeft = (mOffsetLeft + 1) % mEntriesMax;
mEntriesCount--;
return(hold);
}
template<typename T> void PointerDeque<T>::PushRight(T* obj)
{
if (mEntriesCount >= mEntriesMax)
Expand();
mEntries[(mOffsetLeft + mEntriesCount) % mEntriesMax] = obj;
mEntriesCount++;
}
template<typename T> T* PointerDeque<T>::PopRight()
{
if (mEntriesCount == 0)
return(NULL);
mEntriesCount--;
return(mEntries[(mOffsetLeft + mEntriesCount) % mEntriesMax]);
}
template<typename T> T* PointerDeque<T>::PeekLeft()
{
if (mEntriesCount == 0)
return(NULL);
return(mEntries[mOffsetLeft]);
}
template<typename T> T* PointerDeque<T>::PeekRight()
{
if (mEntriesCount == 0)
return(NULL);
return(mEntries[(mOffsetLeft + mEntriesCount - 1) % mEntriesMax]);
}
template<typename T> T* PointerDeque<T>::Peek(int index)
{
if (index >= mEntriesCount)
return(NULL);
return(mEntries[(mOffsetLeft + index) % mEntriesMax]);
}
template<typename T> int PointerDeque<T>::Count()
{
return(mEntriesCount);
}
#endif

View File

@@ -0,0 +1,6 @@
#ifndef _Network_UdpLibrary_H
#define _Network_UdpLibrary_H
#include "UdpHandler.hpp"
#endif//_Network_UdpLibrary_H

View File

@@ -0,0 +1,76 @@
#ifndef UDPHANDLER_HPP
#define UDPHANDLER_HPP
class UdpManager;
class UdpConnection;
class LogicalPacket;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
enum UdpCorruptionReason { cUdpCorruptionNone
, cUdpCorruptionMultiPacket
, cUdpCorruptionReliablePacketTooShort
, cUdpCorruptionInternalPacketTooShort
, cUdpCorruptionDecryptFailed
, cCorruptionReasonZeroLengthPacket
, cCorruptionReasonPacketShorterThanCrcBytes
};
class UdpManagerHandler
{
public:
// This function is called when a listening UdpManager receives a new connection request. If the application wishes to
// accept this connection, it is the responsibility of the application to AddRef the UdpConnection object such that it
// doesn't get destroyed upon returning from the callback. Additionally, the application should set the handler object
// for the connection. See sample code in the UdpLibrary.doc file for an example.
virtual void OnConnectRequest(UdpConnection *con);
// The following functions are called when user-supplied encryption is specified. In particular, the functions may wish
// to query the connection object for the encryption-code it is using. The encryption code is simply a randomly generated
// 32-bit value that the client and server negotiated during the connection-establishment. It can be used as a key
// of sorts for encrypting data uniquely on a per-connection basis. (see UdpConnection::GetEncryptCode())
virtual int OnUserSuppliedEncrypt(UdpConnection *con, uchar *destData, const uchar *sourceData, int sourceLen);
virtual int OnUserSuppliedDecrypt(UdpConnection *con, uchar *destData, const uchar *sourceData, int sourceLen);
virtual int OnUserSuppliedEncrypt2(UdpConnection *con, uchar *destData, const uchar *sourceData, int sourceLen);
virtual int OnUserSuppliedDecrypt2(UdpConnection *con, uchar *destData, const uchar *sourceData, int sourceLen);
};
class UdpConnectionHandler
{
public:
// This function is called whenever an application-packet is ready to be delivered to the application.
// Packets will only ever be delivered to the application during UdpManager::GiveTime calls, so the application
// has complete control of when it willing/able to receive packets.
virtual void OnRoutePacket(UdpConnection *con, const uchar *data, int dataLen) = 0;
// This function is called whenever a UdpManager::EstablishConnection call succeeds in establishing the connection.
// Generally on client-side establishment of a connection, I prefer to sit in a tight loop polling the connection
// to see if it has connected yet or not, rather than using this callback (see sample code)
// note: If it is unable to establish the connection, the OnTerminated callback will be called.
// note: this is a change from previous behavior, see release notes for details.
virtual void OnConnectComplete(UdpConnection *con);
// This function is called anytime the UdpConnection object changes to a cStatusDisconnected state. Every UdpConnection
// object is guaranteed to eventually call this once and only once, even connections that never successfully established.
// note: this is a change from previous behavior, see release notes for details
virtual void OnTerminated(UdpConnection *con);
// This function is called anytime an incoming packet fails the CRC check. Normally these packets are just ignored, as
// corruption does occur from time to time; however, some applications may wish to log these events as often times, they
// are an indication of somebody attempting to hack the data stream.
virtual void OnCrcReject(UdpConnection *con, const uchar *data, int dataLen);
// This function is called anytime a corrupt packet is sensed for some reason.
// The reason we give a callback for it is because you may wish to log it as it could be an early indicator of
// somebody trying to hack the protocol.
virtual void OnPacketCorrupt(UdpConnection *con, const uchar *data, int dataLen, UdpCorruptionReason reason);
};
#endif

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#ifndef _Network_UdpLibrary_H
#define _Network_UdpLibrary_H
#include "UdpLibrary.hpp"
#endif//_Network_UdpLibrary_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,619 @@
#ifndef HASHTABLE_HPP
#define HASHTABLE_HPP
#include <stddef.h>
#include <memory.h>
// This is a simple hash table template. Any type of object can be stored in this hash table
// provided it can be copied. Resizing the table while in use is generally not recommended.
// putting the same object in the table twice is generally not recommended as it makes the find ambiguous
////////////////////////////////////////////////////////
// helper functions for the below hash table classes
////////////////////////////////////////////////////////
inline bool IsPrime(int value) // works on positive numbers up 62,710,561
{
static int sPrimeTab[] =
{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213,
2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,
2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531,
2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617,
2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181,
3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257,
3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511,
3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571,
3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907,
3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139,
4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231,
4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409,
4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493,
4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583,
4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751,
4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831,
4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937,
4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003,
5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087,
5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179,
5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279,
5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387,
5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443,
5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521,
5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639,
5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693,
5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857,
5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939,
5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053,
6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133,
6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221,
6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301,
6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367,
6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473,
6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571,
6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673,
6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761,
6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833,
6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917,
6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997,
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103,
7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207,
7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297,
7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411,
7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499,
7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561,
7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643,
7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723,
7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829,
7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919
};
for (unsigned int j = 0; j < sizeof(sPrimeTab) / sizeof(int) && sPrimeTab[j] * sPrimeTab[j] < value; j++)
{
if (value % sPrimeTab[j] == 0)
return(false);
}
return(true);
}
inline int NextPrime(int value)
{
if (value % 2 == 0)
value++;
while (!IsPrime(value))
value += 2;
return(value);
}
inline int HashString(char *string)
{
int h = 0;
while (*string != 0)
h = ((31 * h) + *string++) ^ (h >> 26);
return(h);
}
inline int UpperHashString(char *string)
{
int h = 0;
while (*string != 0)
{
h = ((31 * h) + (*string >= 'a' && *string <= 'z') ? (*string - 0x20) : *string) ^ (h >> 26);
string++;
}
return(h);
}
struct HashTableStatistics
{
int tableSize;
int usedSlots;
int totalEntries;
};
//////////////////////////////////////////////////////////////////////////
// HashTable
//////////////////////////////////////////////////////////////////////////
template<typename T> class HashTable
{
public:
HashTable(int hashSize);
~HashTable();
void Insert(T& obj, int hashValue);
bool Remove(T& obj, int hashValue);
void Reset(); // removes all entries from the table
T *FindFirst(int hashValue) const; // returns NULL if not found
T *FindNext(T *prevResult) const; // returns NULL if not found
T *WalkFirst() const; // returns NULL if not found
T *WalkNext(T *prevResult) const; // returns NULL if not found
void Resize(int hashSize); // the actual hash size will be rounded up to the next larger prime number (very slow, not recommended)
void GetStatistics(HashTableStatistics *stats) const;
protected:
struct HashEntry
{
T obj;
int hashValue;
HashEntry *nextEntry;
};
HashEntry **mTable;
int mTableSize;
int mEntryCount;
int mStatUsedSlots;
};
template<typename T> HashTable<T>::HashTable(int hashSize)
{
mTable = NULL;
mTableSize = 0;
mEntryCount = 0;
mStatUsedSlots = 0;
Resize(hashSize);
}
template<typename T> HashTable<T>::~HashTable()
{
Reset(); // deletes everything
delete[] mTable;
}
template<typename T> void HashTable<T>::Insert(T& obj, int hashValue)
{
HashEntry *entry = new HashEntry;
entry->obj = obj;
entry->hashValue = hashValue;
int spot = ((unsigned)hashValue) % mTableSize;
if (mTable[spot] == NULL)
{
entry->nextEntry = NULL;
mTable[spot] = entry;
mStatUsedSlots++;
}
else
{
entry->nextEntry = mTable[spot];
mTable[spot] = entry;
}
mEntryCount++;
}
template<typename T> bool HashTable<T>::Remove(T& obj, int hashValue)
{
int spot = ((unsigned)hashValue) % mTableSize;
HashEntry* next = mTable[spot];
HashEntry** prev = &mTable[spot];
while (next != NULL)
{
if (next->obj == obj && next->hashValue == hashValue)
{
*prev = next->nextEntry;
delete next;
mEntryCount--;
if (mTable[spot] == NULL)
mStatUsedSlots--;
return(true);
break;
}
prev = &next->nextEntry;
next = next->nextEntry;
}
return(false);
}
template<typename T> void HashTable<T>::Reset()
{
for (int spot = 0; spot < mTableSize; spot++)
{
HashEntry *curr = mTable[spot];
if (curr != NULL)
{
mStatUsedSlots--;
while (curr != NULL)
{
HashEntry *next = curr->nextEntry;
delete curr;
mEntryCount--;
curr = next;
}
mTable[spot] = NULL;
}
}
}
template<typename T> T *HashTable<T>::FindFirst(int hashValue) const
{
HashEntry *entry = mTable[((unsigned)hashValue) % mTableSize];
while (entry != NULL)
{
if (entry->hashValue == hashValue)
return(&entry->obj);
entry = entry->nextEntry;
}
return(NULL);
}
template<typename T> T *HashTable<T>::FindNext(T *prevResult) const
{
HashEntry *entry = (HashEntry *)(((char *)prevResult) - offsetof(HashEntry, obj));
int hashValue = entry->hashValue;
entry = entry->nextEntry;
while (entry != NULL)
{
if (entry->hashValue == hashValue)
return(&entry->obj);
entry = entry->nextEntry;
}
return(NULL);
}
template<typename T> T *HashTable<T>::WalkFirst() const
{
for (int bucket = 0; bucket < mTableSize; bucket++)
{
HashEntry *entry = mTable[bucket];
if (entry != NULL)
return(&entry->obj);
}
return(NULL);
}
template<typename T> T *HashTable<T>::WalkNext(T *prevResult) const
{
HashEntry *entry = (HashEntry *)(((char *)prevResult) - offsetof(HashEntry, obj));
int bucket = ((unsigned)entry->hashValue) % mTableSize;
entry = entry->nextEntry;
if (entry != NULL)
return(&entry->obj);
bucket++; // go onto next bucket
for (; bucket < mTableSize; bucket++)
{
HashEntry *entry = mTable[bucket];
if (entry != NULL)
return(&entry->obj);
}
return(NULL);
}
template<typename T> void HashTable<T>::Resize(int hashSize)
{
HashEntry **oldTable = mTable;
int oldSize = mTableSize;
// calculate next prime number greater than hashSize.
mTableSize = NextPrime(hashSize);
mTable = new HashEntry*[mTableSize];
memset(mTable, 0, sizeof(HashEntry *) * mTableSize);
mStatUsedSlots = 0;
if (mEntryCount > 0)
{
for (int i = 0; i < oldSize; i++)
{
HashEntry* next = oldTable[i];
while (next != NULL)
{
HashEntry* hold = next;
next = next->nextEntry;
// insert hold into new table
int spot = ((unsigned)hold->hashValue) % mTableSize;
if (mTable[spot] == NULL)
{
hold->nextEntry = NULL;
mTable[spot] = hold;
mStatUsedSlots++;
}
else
{
hold->nextEntry = mTable[spot];
mTable[spot] = hold;
}
}
}
}
delete[] oldTable;
}
template<typename T> void HashTable<T>::GetStatistics(HashTableStatistics *stats) const
{
stats->totalEntries = mEntryCount;
stats->usedSlots = mStatUsedSlots;
stats->tableSize = mTableSize;
}
//////////////////////////////////////////////////////////////////////////////
// ObjectHashTable
//
// similar to basic HashTable object, only this version requires the contents
// be pointers to objects derived from class HashTableMember. If you can use
// this version, it avoids allocations of HashEntry objects.
// making the cost of object inserts/deletes dirt-cheap
//////////////////////////////////////////////////////////////////////////////
class HashTableMember
{
#if defined(_MSC_VER) && (_MSC_VER >= 1300) // MSVC 7.0 is the first version to support friend templates
template<typename T> friend class ObjectHashTable;
protected:
#else
public:
#endif
int mHashValue;
HashTableMember *mHashNextEntry;
};
template<typename T> class ObjectHashTable
{
public:
ObjectHashTable(int hashSize);
~ObjectHashTable();
void Insert(T obj, int hashValue);
bool Remove(T obj, int hashValue);
void Reset(); // removes all entries from the table
T FindFirst(int hashValue) const; // returns NULL if not found
T FindNext(T prevResult) const; // returns NULL if not found
T WalkFirst() const; // returns NULL if not found
T WalkNext(T prevResult) const; // returns NULL if not found
void Resize(int hashSize); // the actual hash size will be rounded up to the next larger prime number (very slow, not recommended)
void GetStatistics(HashTableStatistics *stats) const;
protected:
T *mTable;
int mTableSize;
int mEntryCount;
int mStatUsedSlots;
};
template<typename T> ObjectHashTable<T>::ObjectHashTable(int hashSize)
{
mTable = NULL;
mTableSize = 0;
mEntryCount = 0;
mStatUsedSlots = 0;
Resize(hashSize);
}
template<typename T> ObjectHashTable<T>::~ObjectHashTable()
{
Reset();
delete[] mTable;
}
template<typename T> void ObjectHashTable<T>::Insert(T obj, int hashValue)
{
obj->mHashValue = hashValue;
int spot = ((unsigned)hashValue) % mTableSize;
if (mTable[spot] == NULL)
{
obj->mHashNextEntry = NULL;
mTable[spot] = obj;
mStatUsedSlots++;
}
else
{
obj->mHashNextEntry = mTable[spot];
mTable[spot] = obj;
}
mEntryCount++;
}
template<typename T> bool ObjectHashTable<T>::Remove(T obj, int hashValue)
{
int spot = ((unsigned)hashValue) % mTableSize;
T next = mTable[spot];
T *prev = &mTable[spot];
while (next != NULL)
{
if (next == obj)
{
*prev = (T)next->mHashNextEntry;
next->mHashNextEntry = NULL;
mEntryCount--;
if (mTable[spot] == NULL)
mStatUsedSlots--;
return(true);
break;
}
prev = (T *)&next->mHashNextEntry;
next = (T)next->mHashNextEntry;
}
return(false);
}
template<typename T> void ObjectHashTable<T>::Reset()
{
for (int spot = 0; spot < mTableSize; spot++)
{
T curr = mTable[spot];
if (curr != NULL)
{
while (curr != NULL)
{
T next = (T)curr->mHashNextEntry;
curr->mHashNextEntry = NULL;
mEntryCount--;
curr = next;
}
mTable[spot] = NULL;
mStatUsedSlots--;
}
}
}
template<typename T> T ObjectHashTable<T>::FindFirst(int hashValue) const
{
T entry = mTable[((unsigned)hashValue) % mTableSize];
while (entry != NULL)
{
if (entry->mHashValue == hashValue)
return(entry);
entry = (T)entry->mHashNextEntry;
}
return(NULL);
}
template<typename T> T ObjectHashTable<T>::FindNext(T prevResult) const
{
T entry = prevResult;
int hashValue = entry->mHashValue;
entry = (T)entry->mHashNextEntry;
while (entry != NULL)
{
if (entry->mHashValue == hashValue)
return(entry);
entry = (T)entry->mHashNextEntry;
}
return(NULL);
}
template<typename T> T ObjectHashTable<T>::WalkFirst() const
{
for (int bucket = 0; bucket < mTableSize; bucket++)
{
T entry = mTable[bucket];
if (entry != NULL)
return(entry);
}
return(NULL);
}
template<typename T> T ObjectHashTable<T>::WalkNext(T prevResult) const
{
T entry = prevResult;
int bucket = ((unsigned)entry->mHashValue) % mTableSize;
entry = (T)entry->mHashNextEntry;
if (entry != NULL)
return(entry);
bucket++; // go onto next bucket
for (; bucket < mTableSize; bucket++)
{
entry = mTable[bucket];
if (entry != NULL)
return(entry);
}
return(NULL);
}
template<typename T> void ObjectHashTable<T>::Resize(int hashSize)
{
T *oldTable = mTable;
int oldSize = mTableSize;
// calculate next prime number greater than hashSize.
mTableSize = NextPrime(hashSize);
mTable = new T[mTableSize];
memset(mTable, 0, sizeof(T) * mTableSize);
mStatUsedSlots = 0;
if (mEntryCount > 0)
{
for (int i = 0; i < oldSize; i++)
{
T next = oldTable[i];
while (next != NULL)
{
T hold = next;
next = (T)next->mHashNextEntry;
// insert hold into new table
int spot = ((unsigned)hold->mHashValue) % mTableSize;
if (mTable[spot] == NULL)
{
hold->mHashNextEntry = NULL;
mTable[spot] = hold;
mStatUsedSlots++;
}
else
{
hold->mHashNextEntry = mTable[spot];
mTable[spot] = hold;
}
}
}
}
delete[] oldTable;
}
template<typename T> void ObjectHashTable<T>::GetStatistics(HashTableStatistics *stats) const
{
stats->totalEntries = mEntryCount;
stats->usedSlots = mStatUsedSlots;
stats->tableSize = mTableSize;
}
#endif

View File

@@ -0,0 +1,225 @@
#ifndef PRIORITY_HPP
#define PRIORITY_HPP
template<typename T, typename P> class PriorityQueue;
// classes that wish to be members of the priority queue below must derive themselves from this class
// in order to pull in the two member variables. Unlike normal priority queue classes which don't
// have this restriction, it is required in order to support Remove and reprioritize functionality
// in a timely manner (otherwise, in order to remove an entry that is not at the top, you would have
// to linearly scan the entire queue). This is accomplished by having the member itself contain
// a pointer to it's position in the queue (mPriorityQueuePosition).
// note: a restriction of this ability is that an object cannot participate in more than one priority
// queue at a time.
class PriorityQueueMember
{
public:
PriorityQueueMember();
#if defined(_MSC_VER) && (_MSC_VER >= 1300) // MSVC 7.0 is the first version to support friend templates
template<typename T, typename P> friend class PriorityQueue;
protected:
#else
public:
#endif
int mPriorityQueuePosition; // -1=not in queue
};
// this class provides a priority queue that is capable of reprioritizing/removing entries. The
// compiler will ensure that objects stored in this class are derived from PriorityQueueMember.
// We don't really need this to be a template class, since we could just treat everything as a
// PriorityQueueMember, but then the application would lose some type checking. We don't use references
// in the api as most priority queue templates do as we can't support non pointer types anyways.
template<typename T, typename P> class PriorityQueue
{
public:
PriorityQueue(int queueSize);
~PriorityQueue();
T* Top(); // returns NULL if queue is empty
T* TopRemove(); // returns NULL if queue is empty
T* TopRemove(P priority); // removes item from queue if it has a lower priority value, otherwise return NULL
T* Add(T* entry, P priority); // reprioritizes if already in queue, returns entry always
T* Remove(T* entry); // returns entry always (even if it was not in the queue)
P *GetPriority(T* entry); // returns NULL if entry is not in the queue
int QueueUsed(); // returns how many entries are in the queue
protected:
struct QueueEntry
{
T* entry;
P priority;
};
QueueEntry* mQueue;
int mQueueSize;
int mQueueEnd;
void Refloat(T* entry);
};
//////////////////////////////////////////////////////////////////////////
// PriorityQueueMember implementation
//////////////////////////////////////////////////////////////////////////
inline PriorityQueueMember::PriorityQueueMember()
{
mPriorityQueuePosition = -1;
}
//////////////////////////////////////////////////////////////////////////
// PriorityQueue implementation
//////////////////////////////////////////////////////////////////////////
template<typename T, typename P> PriorityQueue<T, P>::PriorityQueue(int queueSize)
{
mQueueEnd = 0;
mQueueSize = queueSize;
mQueue = new QueueEntry[mQueueSize];
memset(mQueue, 0, sizeof(mQueue));
}
template<typename T, typename P> PriorityQueue<T, P>::~PriorityQueue()
{
delete[] mQueue;
}
template<typename T, typename P> T* PriorityQueue<T, P>::Top()
{
if (mQueueEnd == 0)
return(NULL);
return(mQueue[0].entry);
}
template<typename T, typename P> T* PriorityQueue<T, P>::TopRemove()
{
if (mQueueEnd == 0)
return(NULL);
T* top = mQueue[0].entry;
Remove(top);
return(top);
}
template<typename T, typename P> T* PriorityQueue<T, P>::TopRemove(P priority)
{
if (mQueueEnd > 0 && mQueue[0].priority <= priority)
return(Remove(mQueue[0].entry));
return(NULL);
}
template<typename T, typename P> P* PriorityQueue<T, P>::GetPriority(T* entry)
{
if (entry->mPriorityQueuePosition >= 0)
return(&mQueue[entry->mPriorityQueuePosition].priority);
return(NULL);
}
template<typename T, typename P> T* PriorityQueue<T, P>::Add(T* entry, P priority)
{
if (entry->mPriorityQueuePosition == -1)
{
// not in queue, so add it to the bottom
if (mQueueEnd >= mQueueSize)
return(NULL);
mQueue[mQueueEnd].entry = entry;
mQueue[mQueueEnd].priority = priority;
mQueue[mQueueEnd].entry->mPriorityQueuePosition = mQueueEnd;
mQueueEnd++;
}
else
{
// see if priority has actually changed, if not, just return, otherwise change priority and fall through to refloat it
if (mQueue[entry->mPriorityQueuePosition].priority == priority)
return(entry);
mQueue[entry->mPriorityQueuePosition].priority = priority;
}
Refloat(entry);
return(entry);
}
template<typename T, typename P> T* PriorityQueue<T, P>::Remove(T* entry)
{
if (entry->mPriorityQueuePosition == -1)
return(entry);
// move end entry into place of one being removed
mQueueEnd--;
int spot = entry->mPriorityQueuePosition;
if (spot != mQueueEnd) // don't remove last item in queue (bottom of tree), so no need to copy bottom one up and refloat it (we would be refloating our own removed entry)
{
mQueue[spot] = mQueue[mQueueEnd];
mQueue[spot].entry->mPriorityQueuePosition = spot;
Refloat(mQueue[spot].entry);
}
entry->mPriorityQueuePosition = -1;
return(entry);
}
template<typename T, typename P> void PriorityQueue<T, P>::Refloat(T* entry)
{
// float upward
int spot = entry->mPriorityQueuePosition;
bool tryDown = true;
while (spot > 0 && mQueue[spot].priority < mQueue[(spot - 1) / 2].priority)
{
int newSpot = (spot - 1) / 2;
QueueEntry hold = mQueue[spot];
mQueue[spot] = mQueue[newSpot];
mQueue[newSpot] = hold;
mQueue[spot].entry->mPriorityQueuePosition = spot;
mQueue[newSpot].entry->mPriorityQueuePosition = newSpot;
spot = newSpot;
tryDown = false;
}
if (tryDown)
{
// if we didn't manage to float up at all, then we need to try floating down
for (;;)
{
// pick smallest child
int downSpot1 = (spot * 2) + 1;
if (downSpot1 >= mQueueEnd)
break;
int downSpot2 = (spot * 2) + 2;
if (downSpot2 >= mQueueEnd || mQueue[downSpot1].priority < mQueue[downSpot2].priority)
{
if (mQueue[downSpot1].priority < mQueue[spot].priority)
{
QueueEntry hold = mQueue[spot];
mQueue[spot] = mQueue[downSpot1];
mQueue[downSpot1] = hold;
mQueue[spot].entry->mPriorityQueuePosition = spot;
mQueue[downSpot1].entry->mPriorityQueuePosition = downSpot1;
spot = downSpot1;
}
else
break;
}
else
{
if (mQueue[downSpot2].priority < mQueue[spot].priority)
{
QueueEntry hold = mQueue[spot];
mQueue[spot] = mQueue[downSpot2];
mQueue[downSpot2] = hold;
mQueue[spot].entry->mPriorityQueuePosition = spot;
mQueue[downSpot2].entry->mPriorityQueuePosition = downSpot2;
spot = downSpot2;
}
else
break;
}
}
}
}
template<typename T, typename P> int PriorityQueue<T, P>::QueueUsed()
{
return(mQueueEnd);
}
#endif

View File

@@ -0,0 +1,245 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#ifdef WIN32
#include <conio.h>
#endif
#include <ctype.h>
#include <sys\stat.h>
#include <sys\types.h>
#include <math.h>
#include <malloc.h>
#include <windows.h>
#ifdef WIN32
#ifdef _DEBUG
#include <crtdbg.h>
#endif
#endif
#include "UdpLibrary.hpp"
class MyConnectionHandler : public UdpConnectionHandler
{
public:
virtual void OnRoutePacket(UdpConnection *con, const uchar *data, int dataLen);
};
int main(int argc, char **argv)
{
#ifdef _DEBUG
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif
printf("UdpLibrary Test Client, press SHIFT-F12 to terminate.\n");
printf(" /IP:xxx.xxx.xxx.xxx\n");
printf(" /PORT:xxx\n");
char connectIp[256];
strcpy(connectIp, "127.0.0.1");
int connectPort = 9950;
for (int i = 0; i < argc; i++)
{
if (memicmp(argv[i], "/IP:", 4) == 0)
strcpy(connectIp, argv[i] + 4);
if (memicmp(argv[i], "/PORT:", 6) == 0)
connectPort = atoi(argv[i] + 6);
}
//////////////////////////////////////////////////
// initialize everything
//////////////////////////////////////////////////
srand(clock());
UdpManager::Params params;
params.clockSyncDelay = 45000;
params.crcBytes = 2;
params.hashTableSize = 10;
params.incomingBufferSize = 32 * 1024;
params.keepAliveDelay = 8000;
params.portAliveDelay = 5000;
params.maxConnections = 3;
params.maxDataHoldSize = 400;
params.maxDataHoldTime = 60;
params.maxRawPacketSize = 496;
params.outgoingBufferSize = 32 * 1024;
params.packetHistoryMax = 1000;
params.port = 0;
params.pooledPacketMax = 50;
params.pooledPacketSize = 512;
#if 0
params.simulateIncomingByteRate = 0;
params.simulateIncomingLossPercent = 10;
params.simulateOutgoingByteRate = 0;
params.simulateOutgoingLossPercent = 10;
params.simulateDestinationOverloadLevel = 0;
params.simulateOutgoingOverloadLevel = 0;
#endif
params.reliable[0].maxInstandingPackets = 500;
params.reliable[0].maxOutstandingBytes = 200000;
params.reliable[0].maxOutstandingPackets = 500;
params.reliable[0].outOfOrder = false;
params.reliable[0].trickleRate = 0;
params.reliable[0].trickleSize = 0;
params.reliable[0].processOnSend = true;
params.reliable[1].maxInstandingPackets = 20;
params.reliable[1].maxOutstandingBytes = 5000;
params.reliable[1].maxOutstandingPackets = 30;
params.reliable[1].outOfOrder = false;
params.reliable[1].trickleRate = 200;
params.reliable[1].trickleSize = 200;
params.reliable[2] = params.reliable[0];
params.reliable[2].outOfOrder = true;
params.reliable[3] = params.reliable[1];
params.reliable[3].outOfOrder = true;
UdpManager *myUdpManager = new UdpManager(&params);
// establish connection
MyConnectionHandler myConnectionHandler;
printf("Connecting to: %s,%d.", connectIp, connectPort);
UdpConnection *myConnection = myUdpManager->EstablishConnection(connectIp, connectPort);
myConnection->SetHandler(&myConnectionHandler);
assert(myConnection != NULL);
int count = 0;
while (myConnection->GetStatus() == UdpConnection::cStatusNegotiating)
{
myUdpManager->GiveTime();
Sleep(50);
if ((count++ % 20) == 0)
printf(".");
}
printf("\n");
//////////////////////////////////////////////////
// master loop (sending data)
//////////////////////////////////////////////////
count = 0;
for (;;)
{
// check for shutdown keys
if (kbhit())
{
int k = getch();
if ((k == 0 || k == 0xe0) && (getch() == 0x88)) // hit shift-F12 to exit gracefully
break;
if (k == 32)
{
// hit space bar to see statistics
UdpConnectionStatistics stats;
myConnection->GetStats(&stats);
char hold[256];
printf("%s,%d AVE=%d HIGH=%d LOW=%d MSTR=%d,%d CRC=%I64d ORD=%I64d %I64d<<%I64d %I64d>>%I64d\n", myConnection->GetDestinationIp().GetAddress(hold), myConnection->GetDestinationPort()
, stats.averagePingTime, stats.highPingTime, stats.lowPingTime, stats.masterPingTime, stats.masterPingAge, stats.crcRejectedPackets, stats.orderRejectedPackets, stats.syncOurReceived, stats.syncTheirSent
, stats.syncOurSent, stats.syncTheirReceived);
}
if (k == 'd')
{
myConnection->Disconnect(5000); // disconnect when channel is clear
printf("Disconnecting... (giving connection time to flush)\n");
}
}
// see if server terminated out connection, if so, break out and exit app
if (myConnection->GetStatus() == UdpConnection::cStatusDisconnected)
{
printf("Connection broken.\n");
break;
}
#if 1
// randomly send a medium sized packet on a random channel
if (rand() % 200 == 0)
{
char buf[8000];
for (int i = 1; i < sizeof(buf); i++)
{
buf[i] = (char)(i % 100);
}
int pc = rand() % 5;
for (i = 0; i < pc; i++)
{
buf[0] = (char)(rand() % 50);
int len = (rand() % 1800 + 2);
printf("OUTLEN=%d \n", len);
myConnection->Send(cUdpChannelReliable1, buf, len);
}
}
#elif 0
// send a very large packet one after the other (don't send next packet til the previous one has made it)
if (myConnection->TotalPendingBytes() == 0)
{
// send another packet
SimpleLogicalPacket *lp = new SimpleLogicalPacket(NULL, 30000000);
int dlen = lp->GetDataLen();
char *ptr = (char *)lp->GetDataPtr();
ptr[0] = (char)(rand() % 50);
for (int i = 1; i < dlen; i++)
{
ptr[i] = (char)(i % 100);
}
printf("OUT LEN=%d \n", dlen);
myConnection->Send(cUdpChannelReliable1, lp);
lp->Release();
}
#else
// prepare a random sized group of medium packets and then send the group, don't prepare next group until previous one has made it
UdpConnection::ChannelStatus cs;
myConnection->GetChannelStatus(cUdpChannelReliable1, &cs);
if (cs.queuedBytes == 0)
{
int count = 0;
GroupLogicalPacket *glp = new GroupLogicalPacket();
int di = rand() % 20 + 1;
for (int i = 0; i < di; i++)
{
GroupLogicalPacket *sub = new GroupLogicalPacket();
for (int j = 0; j < di; j++)
{
char buf[8000];
*(ushort *)buf = count;
int len = (rand() % 1000) + 10;
*(ushort *)(buf + len - 2) = count;
sub->AddPacket(buf, len);
count++;
}
glp->AddPacket(sub);
sub->Release();
}
myConnection->Send(cUdpChannelReliable1, glp);
glp->Release();
printf("Group of %d packets sent\n", count);
}
#endif
myUdpManager->GiveTime();
Sleep(10);
}
//////////////////////////////////////////////////
// terminate everything
//////////////////////////////////////////////////
myConnection->Release();
myUdpManager->Release();
return(0);
}
void MyConnectionHandler::OnRoutePacket(UdpConnection * /*con*/, const uchar *data, int dataLen)
{
printf("IN=%d/%d LEN=%d \n", *(ushort *)data, *(ushort *)(data + dataLen - 2), dataLen);
}

View File

@@ -0,0 +1,152 @@
# Microsoft Developer Studio Project File - Name="udplibrary" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Static Library" 0x0104
CFG=udplibrary - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "udplibrary.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "udplibrary.mak" CFG="udplibrary - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "udplibrary - Win32 Release" (based on "Win32 (x86) Static Library")
!MESSAGE "udplibrary - Win32 Optimized" (based on "Win32 (x86) Static Library")
!MESSAGE "udplibrary - Win32 Debug" (based on "Win32 (x86) Static Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName "udplibrary"
# PROP Scc_LocalPath "."
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "udplibrary - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "..\..\..\..\compile\win32\udplibrary\Release"
# PROP Intermediate_Dir "..\..\..\..\compile\win32\udplibrary\Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD CPP /nologo /MT /W4 /WX /GX /Zi /O2 /I "..\stlport453\stlport" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "udplibrary - Win32 Optimized"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Optimized"
# PROP BASE Intermediate_Dir "Optimized"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "..\..\..\..\compile\win32\udplibrary\Optimized"
# PROP Intermediate_Dir "..\..\..\..\compile\win32\udplibrary\Optimized"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /MTd /W4 /WX /Gm /GX /Zi /Od /I "..\stlport453\stlport" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FD /GZ /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "udplibrary - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "..\..\..\..\compile\win32\udplibrary\Debug"
# PROP Intermediate_Dir "..\..\..\..\compile\win32\udplibrary\Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /MTd /W4 /WX /Gm /GX /Zi /Od /I "..\stlport453\stlport" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FD /GZ /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ENDIF
# Begin Target
# Name "udplibrary - Win32 Release"
# Name "udplibrary - Win32 Optimized"
# Name "udplibrary - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\UdpLibrary.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\hashtable.hpp
# End Source File
# Begin Source File
SOURCE=.\PointerDeque.hpp
# End Source File
# Begin Source File
SOURCE=.\priority.hpp
# End Source File
# Begin Source File
SOURCE=.\UdpHandler.h
# End Source File
# Begin Source File
SOURCE=.\UdpHandler.hpp
# End Source File
# Begin Source File
SOURCE=.\UdpLibrary.h
# End Source File
# Begin Source File
SOURCE=.\UdpLibrary.hpp
# End Source File
# End Group
# End Target
# End Project

View File

@@ -0,0 +1,290 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <conio.h>
#include <ctype.h>
#include <sys\stat.h>
#include <sys\types.h>
#include <math.h>
#include <malloc.h>
#include <windows.h>
#include <winsock.h>
#ifdef _DEBUG
#include <crtdbg.h>
#endif
#include "UdpLibrary.hpp"
class Player : public UdpConnectionHandler
{
public:
Player(UdpConnection *con);
virtual ~Player();
virtual void OnRoutePacket(UdpConnection *con, const uchar *data, int dataLen);
public:
UdpConnection *mConnection;
};
class PlayerManager : public UdpManagerHandler
{
public:
PlayerManager();
~PlayerManager();
void AddPlayer(Player *player);
void GiveTime();
void DumpStats();
void SendPacketToAll(UdpChannel channel, void *data, int dataLen);
virtual void OnConnectRequest(UdpConnection *con);
protected:
Player *mPlayers[5000];
int mPlayersCount;
UdpMisc::ClockStamp mStartPacketTime;
int mLastIncomingLargeSoFar;
};
void MyCallbackRoutePacket(void *mainPassThrough, UdpConnection *con, const uchar *data, int dataLen);
void MyCallbackConnectRequest(void *mainPassThrough, UdpConnection *con);
UdpManager *myUdpManager;
int main(int argc, char **argv)
{
printf("UdpLibrary Test Server, press SHIFT-F12 to terminate.\n");
printf(" /PORT:xxx\n");
int listenPort = 9950;
for (int i = 0; i < argc; i++)
{
if (memicmp(argv[i], "/PORT:", 6) == 0)
listenPort = atoi(argv[i] + 6);
}
#ifdef _DEBUG
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif
//////////////////////////////////////////////////
// initialize everything
//////////////////////////////////////////////////
srand(clock());
PlayerManager *myPlayerManager = new PlayerManager();
UdpManager::Params params;
params.handler = myPlayerManager;
params.crcBytes = 2;
params.encryptMethod[0] = UdpManager::cEncryptMethodXorBuffer;
params.hashTableSize = 1000;
params.incomingBufferSize = 256 * 1024;
params.outgoingBufferSize = 256 * 1024;
params.clockSyncDelay = 0;
params.keepAliveDelay = 0;
params.maxConnections = 4000;
params.maxDataHoldSize = 400;
params.maxDataHoldTime = 60;
params.maxRawPacketSize = 256;
params.packetHistoryMax = 1000;
params.port = listenPort;
params.pooledPacketMax = 5000;
params.pooledPacketSize = 512;
#if 0
params.simulateIncomingByteRate = 2000;
params.simulateIncomingLossPercent = 0;
params.simulateOutgoingByteRate = 2000;
params.simulateOutgoingLossPercent = 0;
params.simulateDestinationOverloadLevel = 8000;
params.simulateOutgoingOverloadLevel = 8000;
#endif
params.reliable[0].maxInstandingPackets = 500;
params.reliable[0].maxOutstandingBytes = 200000;
params.reliable[0].maxOutstandingPackets = 500;
params.reliable[0].outOfOrder = false;
params.reliable[0].trickleRate = 0;
params.reliable[0].trickleSize = 0;
params.reliable[1].maxInstandingPackets = 30;
params.reliable[1].maxOutstandingBytes = 200000;
params.reliable[1].maxOutstandingPackets = 30;
params.reliable[1].outOfOrder = false;
params.reliable[1].trickleRate = 200;
params.reliable[1].trickleSize = 200;
params.reliable[2] = params.reliable[0];
params.reliable[2].outOfOrder = true;
params.reliable[3] = params.reliable[1];
params.reliable[3].outOfOrder = true;
myUdpManager = new UdpManager(&params);
//////////////////////////////////////////////////
// master loop (processing incoming data/connections)
//////////////////////////////////////////////////
printf("Listening on port %d\n", listenPort);
int count = 0;
for (;;)
{
// check for shutdown keys
if (kbhit())
{
int k = getch();
if ((k == 0 || k == 0xe0) && (getch() == 0x88))
break;
if (k == 32)
myPlayerManager->DumpStats();
}
if ((rand() % 300) == 0)
{
count++;
char buf[2000];
*(ushort *)buf = (ushort)count;
int len = (rand() % 1000) + 10;
*(ushort *)(buf + len - 2) = (ushort)count;
myPlayerManager->SendPacketToAll(cUdpChannelReliable1, buf, len);
printf("OUT=%d/%d LEN=%d \n", *(ushort *)buf, *(ushort *)(buf + len - 2), len);
}
myUdpManager->GiveTime();
myPlayerManager->GiveTime();
Sleep(10);
}
//////////////////////////////////////////////////
// terminate everything
//////////////////////////////////////////////////
delete myPlayerManager;
myUdpManager->Release();
return(0);
}
////////////////////////////////////////
// Player implementation
////////////////////////////////////////
Player::Player(UdpConnection *con)
{
mConnection = con;
mConnection->AddRef();
mConnection->SetHandler(this);
char hold[256];
printf("CONNECTION %s,%d \n", mConnection->GetDestinationIp().GetAddress(hold), mConnection->GetDestinationPort());
}
Player::~Player()
{
char hold[256];
printf("TERMINATE %s,%d \n", mConnection->GetDestinationIp().GetAddress(hold), mConnection->GetDestinationPort());
mConnection->SetHandler(NULL);
mConnection->Disconnect();
mConnection->Release();
}
void Player::OnRoutePacket(UdpConnection * /*con*/, const uchar *data, int dataLen)
{
for (int i = 1; i < dataLen; i++)
{
bool match = (data[i] == (i % 100));
assert(match);
}
char hold[256];
printf("FROM=%s,%d LEN=%d \n", mConnection->GetDestinationIp().GetAddress(hold), mConnection->GetDestinationPort(), dataLen);
#if 0
// reflect exact packet back to client
mConnection->Send(cUdpChannelReliable1, data, dataLen);
#endif
}
////////////////////////////////////////
// PlayerManager implementation
////////////////////////////////////////
PlayerManager::PlayerManager()
{
mPlayersCount = 0;
mStartPacketTime = 0;
mLastIncomingLargeSoFar = 90000000;
}
PlayerManager::~PlayerManager()
{
for (int i = mPlayersCount - 1; i >= 0; i--)
delete mPlayers[i];
}
void PlayerManager::OnConnectRequest(UdpConnection *con)
{
AddPlayer(new Player(con));
}
void PlayerManager::AddPlayer(Player *player)
{
mPlayers[mPlayersCount++] = player;
}
void PlayerManager::GiveTime()
{
// see if the player object is no longer connected
for (int i = 0; i < mPlayersCount; i++)
{
if (mPlayers[i]->mConnection->GetStatus() == UdpConnection::cStatusDisconnected || mPlayers[i]->mConnection->LastReceive() > 2000000)
{
Player *p = mPlayers[i];
mPlayersCount--;
memmove(&mPlayers[i], &mPlayers[i + 1], (mPlayersCount - i) * sizeof(Player *));
i--;
delete p;
}
}
if (mPlayersCount > 0)
{
UdpConnection::ChannelStatus cs;
mPlayers[0]->mConnection->GetChannelStatus(cUdpChannelReliable1, &cs);
UdpManagerStatistics ms;
myUdpManager->GetStats(&ms);
if (cs.incomingLargeSoFar < mLastIncomingLargeSoFar)
mStartPacketTime = UdpMisc::Clock();
mLastIncomingLargeSoFar = cs.incomingLargeSoFar;
int e = UdpMisc::ClockElapsed(mStartPacketTime);
if (e > 0)
fprintf(stderr, "%d of %d (%d bps)(%d) \r", cs.incomingLargeSoFar, cs.incomingLargeTotal, (int)(((__int64)cs.incomingLargeSoFar * 1000) / (__int64)e), ms.packetsReceived);
}
}
void PlayerManager::SendPacketToAll(UdpChannel channel, void *data, int dataLen)
{
LogicalPacket *lp = myUdpManager->CreatePacket(data, dataLen);
for (int i = 0; i < mPlayersCount; i++)
{
mPlayers[i]->mConnection->Send(channel, lp);
}
lp->Release();
}
void PlayerManager::DumpStats()
{
for (int i = 0; i < mPlayersCount; i++)
{
UdpConnectionStatistics stats;
mPlayers[i]->mConnection->GetStats(&stats);
char hold[256];
printf("%s,%d AVE=%d HIGH=%d LOW=%d MSTR=%d,%d CRC=%I64d ORD=%I64d %I64d<<%I64d %I64d>>%I64d\n", mPlayers[i]->mConnection->GetDestinationIp().GetAddress(hold), mPlayers[i]->mConnection->GetDestinationPort()
, stats.averagePingTime, stats.highPingTime, stats.lowPingTime, stats.masterPingTime, stats.masterPingAge, stats.crcRejectedPackets, stats.orderRejectedPackets, stats.syncOurReceived, stats.syncTheirSent
, stats.syncOurSent, stats.syncTheirReceived);
}
}

View File

@@ -1,2 +1,3 @@
add_subdirectory(3rd)
add_subdirectory(ours)