我需要将UDP数据包的前5个字节与两个定义进行比较,如果它匹配一个,则相应地对它们进行操作。但是,我应该如何代表Hex,因为这显然不会/不起作用?
注释行是我正在做的原始方式,但效率不高。
private static void HandleQuery(Socket socket, EndPoint Remote)
{
byte[] A2S_INFO_REQUEST = StringToByteArray("\xFF\xFF\xFF\xFF\x54");
byte[] A2S_PLAYER = StringToByteArray("\xFF\xFF\xFF\xFF\x55");
byte[] data = new byte[1400];
int recv = socket.ReceiveFrom(data, ref Remote);
// A2S_INFO QUERY
//if (recv == 25 && data[4] == 84)
if (CompareByteArray(A2S_INFO_REQUEST, data, 5))
{
ReplyInfoQuery(socket, Remote);
}
// A2S_PLAYER QUERY
//if (recv == 9)
if (CompareByteArray(A2S_PLAYER, data, 5))
{
ReplyPlayerQuery(socket, Remote);
}
}
private static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
private static bool CompareByteArray(byte[] a1, byte[] a2, int len)
{
for (int i = 0; i < len; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}
return true;
}
答案 0 :(得分:2)
您可以更轻松地填充字节数组:
//byte[] A2S_PLAYER = StringToByteArray("\xFF\xFF\xFF\xFF\x55");
byte[] A2S_PLAYER = new byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x55} ;
答案 1 :(得分:0)
我建议将你的5个字节转换为long(System.Int64)。这样你甚至可以使用开关/案例来发送你的请求。