[英]Splitting up UDP packet
我正在使用UdpClient來查詢游戲服務器的服務器名稱,地圖,玩家數量等。
我已遵循此頁面上的指南(A2S_INFO) http://developer.valvesoftware.com/wiki/Server_queries#Source_servers
我得到了正確的答復:
替代文字http://data.fuskbugg.se/skalman01/reply.JPG
我不知道我將如何獲取每個信息塊(服務器名稱,地圖等)。
有什么幫助嗎? 我假設有人必須查看鏈接的Wiki中指定的回復格式,但是我不知道該怎么做。
回復格式為您提供了回復數據包中字段的順序和類型,基本上就像一個結構。 您可以使用BinaryReader
類的類來讀取數據包中的字節組,並將其解釋為適當的數據類型。
您如何得到回應?
MemoryStream
。 我認為UdpClient
就是這樣做的。 然后,使用該流構造BinaryReader
。 記住,流和閱讀器都需要Disposed
。
BinaryReader reader = new BinaryReader(stream);
現在,您可以使用與字段類型相對應的方法來調用讀取器的方法,如ReadByte
, ReadInt32
等,以從響應中依次讀取每個字段。 流在讀取時會更新其內部偏移量,因此您可以從響應緩沖區中的正確位置自動讀取連續的字段。 BinaryReader
已經具有適用於Steam數據包中使用的五種非字符串類型的方法:
byte: ReadByte
short: ReadInt16
long: ReadInt32
float: ReadSingle
long long: ReadUInt64
(是的,里面有一個U; Valve頁面說這些是未簽名的) string
有點棘手,因為BinaryReader
還沒有方法以Valve(空終止的UTF-8)指定的格式讀取字符串,因此您必須自己逐字節進行操作。 為了使它看起來與其他BinaryReader
方法盡可能地相似,您可以編寫一個擴展方法(未經測試的代碼;這是它的要旨):
public static string ReadSteamString(this BinaryReader reader)
{
// To hold the list of bytes making up the string
List<byte> str = new List<byte>();
byte nextByte = reader.ReadByte();
// Read up to and including the null terminator...
while (nextByte != 0)
{
// ...but don't include it in the string
str.Add(nextByte);
nextByte = reader.ReadByte();
}
// Interpret the result as a UTF-8 sequence
return Encoding.UTF8.GetString(str.ToArray());
}
您提供的響應數據包的一些用法示例:
// Returns -1, corresponding to FF FF FF FF
int header = reader.ReadInt32();
// Returns 0x49, for packet type
byte packetType = reader.ReadByte();
// Returns 15, for version
byte ver = reader.ReadByte();
// Returns "Lokalen TF2 #03 All maps | Vanilla"
string serverName = reader.ReadSteamString();
// Returns "cp_well"
string mapName = reader.ReadSteamString();
// etc.
您可以使用類似的代碼通過BinaryWriter
創建請求數據包,而不是手動組裝單個字節值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.