GameLoop.Networking
1.0.0
用於 GameLoop 中製作的遊戲的 UDP 網路庫!它提供了多個抽象級別,從低級簡單 UDP 包裝器到更高級別的包裝器。
// Spin up a socket listener. It listens for datagrams from any network address, on the specified port.
var peer = new NetworkSocket ( memoryPool ) ;
peer . Bind ( new IPEndPoint ( IPAddress . Any , port ) ) ;
// Send data. It sends data to the specified network address and port.
peer . SendTo ( new IPEndPoint ( IPAddress . Loopback , port ) ) ;
// Polling for data. It fetches a message from the receiving queue, if any. If nothing has been received, it just returns "false".
while ( peer . Poll ( out NetworkArrivedData message ) )
{
var addressFrom = message . EndPoint ;
var receivedData = message . Data
// Execute your logic on received data.
}
該庫不直接分配記憶體。相反,它將此職責委託給兩個介面:IMemoryPool 和 IMemoryAllocator。透過實作這些接口,您可以操縱應用程式中記憶體的分配和管理方式。該庫包含一個簡單的分配器和一個簡單的池,您可以使用它快速建立原型。
var memoryAllocator = new SimpleManagedAllocator ( ) ;
var memoryPool = new SimpleMemoryPool ( memoryAllocator ) ;
該庫包含一些方便的結構來處理緩衝區,以幫助使用者向緩衝區寫入/讀取緩衝區。
// Reading from a buffer.
byte [ ] buffer = message . Data ;
var reader = default ( NetworkReader ) ;
reader . Initialize ( ref buffer ) ;
int myInt = reader . ReadInt ( ) ;
long myLong = reader . ReadLong ( ) ;
float myFloat = reader . ReadFloat ( ) ;
string myString = reader . ReadString ( ) ;
// etc
// Writing to a buffer.
var writer = default ( NetworkWriter ) ;
// 1) You can manually manage the buffer:
/* 1) */ byte [ ] buffer = memoryPool . Rent ( size ) ;
/* 1) */ writer . Initialize ( ref buffer ) ;
// NOTE: in this way the writer will NOT expand the buffer if a Write call requires more space.
// OR
// 2) You can let the writer to manage internally the buffer:
/* 2) */ writer . Initialize ( memoryPool , initialSize ) ;
// NOTE: this will automatically expand the buffer if a Write call requires more space.
// OR
// 3) You can pass a buffer to copy its initial state, but let the writer to manage its own buffer internally:
/* 3) */ byte [ ] initialState = memoryPool . Rent ( size ) ;
/* 3) */ writer . Initialize ( memoryPool , ref initialState ) ;
// NOTE: this will automatically expand the buffer if a Write call requires more space.
writer . Write ( 12 ) ;
writer . Write ( 24f ) ;
writer . Write ( "36" ) ;
// etc