读书人

C# C/S登陆模块 服务器不分辨客户端的

发布时间: 2013-09-13 21:12:00 作者: rapoo

C# C/S登陆模块 服务器不识别客户端的请求
在客户端:
command = Encoding.ASCII.GetBytes("Login"); //命令
for (int i = 0; i < command.Length; i++)
{
cmd[i]=command[i];
}
memStream = new MemoryStream();
formatter.Serialize(memStream, user);
memStream.Flush();
data = memStream.ToArray(); //将User对象序列化发送给服务器
buffer=new byte[cmd.Length+data.Length];
Array.Copy(cmd,0,buffer,0,cmd.Length);
Array.Copy(data,0,buffer,cmd.Length,data.Length);
contactWithServer.sendData(buffer,buffer.Length);
public void sendData(byte[] data,int len)
{
udpSendClient.Send(data,len,sendIpep);
}
服务器端:
data = receiveUdpClient.Receive(ref receiveIpep);
MessageBox.Show(data.Length.ToString(),"数据长度");
int i = 0;


for ( i = 0; i < 20; i++)
{
if (Convert.ToInt32(data[i]) == 0)
{
//MessageBox.Show("检测到0");
break;
}
else
command[i] = data[i];
}
MessageBox.Show(i.ToString(),"i的值"); //输出i的值是5
commandStr = Encoding.ASCII.GetString(command);
MessageBox.Show(commandStr);//打印出来的值是Login
可是不知道为什么转化后的commandStr的值和字符串"Login"的值不等,所有这个switch不执行 case"Login",一直执行的是default
switch (commandStr)
{
case "Login":
MessageBox.Show("hello");
default:MessageBox.Show("没有收到有效请求");


}
大家帮忙分析分析,这是啥原因...这是我想的服务器和客户端沟通的笨办法,希望大家多指导下

[解决办法]
commandStr.Trim() 说不定是有尾空格,你的 Encoding.ASCII.GetString 未指定 command 的有效长度。
[解决办法]

引用:
Quote: 引用:

commandStr.Trim() 说不定是有尾空格,你的 Encoding.ASCII.GetString 未指定 command 的有效长度。

commandStr.Trim()试过了,还是不行。。。我以前也是这么接收命令的,可以接收成功,不过当时命令和数据是分开传送的。
Encoding.ASCII.GetString 未指定 command 的有效长度 应该也不是这个原因

肯定是有地方搞错了,
MessageBox.Show(commandStr.Length) 是不是 5

读书人网 >C#

热点推荐