我试图运行一个简单的Udp服务器和客户端,但在客户端收到不正确的数据。
在服务器上,使用此方法构造字节数组:
public byte[] CreateReplyPacket(byte[] data) {
List<byte> dataStream = new List<byte>();
userCommand = (Globals.Command)BitConverter.ToInt32(data, 0);
switch (userCommand) {
case Globals.Command.Connect:
dataStream.Clear();
dataStream.AddRange(BitConverter.GetBytes((int)userCommand));
Console.WriteLine("Incoming Connection ...");
break;
case Globals.Command.Login:
int usernameLength = BitConverter.ToInt32(data, 4);
int passwordLength = BitConverter.ToInt32(data, 8);
if (usernameLength > 0)
username = Encoding.UTF8.GetString(data, 12, usernameLength);
if (passwordLength > 0)
password = Encoding.UTF8.GetString(data, 12 + usernameLength, passwordLength);
bool loginAttempt = Database.LoginAttempt(username, password);
dataStream.Clear();
dataStream.AddRange(BitConverter.GetBytes((int)userCommand));
dataStream.AddRange(BitConverter.GetBytes(loginAttempt));
break;
}
return dataStream.ToArray();
}
模拟不成功的登录尝试,我得到的字节数组是01-00-00-00-00。一个整数后跟一个布尔值,这正是想要的。布尔值是最后一个00,表示错误。
但在客户端,我得到的是:01-00-00-00-07。我不知道7是什么,但是它将我的布尔值从false变为true,这显然非常糟糕。
这是处理传入字节数组的客户端代码:
private void OnReceive(IAsyncResult AR) {
int rec = clientSocket.EndReceiveFrom(AR, ref epServer);
byte[] tmpData = new byte[rec];
Buffer.BlockCopy(byteData, 0, tmpData, 0, rec);
Debug.Log(BitConverter.ToString(tmpData));
Globals.Command cmdReceived = (Globals.Command)BitConverter.ToInt32(tmpData, 0);
if (cmdReceived == Globals.Command.Connect) {
messageToDisplay = "Connected to the Server";
} else if (cmdReceived == Globals.Command.Login) {
if (BitConverter.ToBoolean(tmpData, 4)) {
messageToDisplay = "Succesfully Logged in";
isAuthenticated = true;
} else {
messageToDisplay = "Wrong Username or Password";
}
}
clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
}
这对我来说是一个非常新的概念,也是我对StackOverflow的第一篇文章,所以我必须道歉答案是显而易见的。或者,如果我在代码中遗漏了其他重要内容。