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