我不是伸手党,只是这个问题我疯了.....
做的是一个仿QQ。。客户端和服务器之间传输包的时候...我是这样处理的....
先传长度,再接收指定长度
之前还可以,10多天没碰它,突然不行了....
我感到很奇怪...发代码上来给 大神们看看,望帮忙下.....我下面加了for循环之后 就一切正常
我想请问 要怎么修改这段代码啊....太强的理论就算了!!
先谢过.....................
- C# code
发送消息 information temp = new information(); temp.command = "02"; temp.values = _username; byte[] bt = SerializeObject(temp); int len = bt.Length; byte[] m = System.BitConverter.GetBytes(len); _nws.Write(m, 0, 4); _nws.Write(bt, 0, bt.Length); 接收消息: byte[] buffer = new byte[4096]; int offset = 0; int count = 4; int datalen; while (true) { int len = _nws.Read(buffer, offset, count); //读入4个字节,一个int表示要接受包的长度 if (len != count) { offset += len; count -= len; continue; } datalen = BitConverter.ToInt32(buffer, 0); offset = 0; count = 4; break; } int lent = datalen; if (datalen > 0) { int offsett = 0; while (datalen > 0) { int len = _nws.Read(buffer, offset, datalen); if (len != datalen) { offsett += len; datalen -= len; continue; } break; } } for (int itm = 0; itm < 50000000; ++itm) //加了for循环就可以了! { } //MessageBox.Show(string.Format("接受了{0}", lent)); information temp = new information(); temp = (information)DeserializeObject(buffer); //反序列化
[解决办法]
代码不完整也没有看到你的错误信息。代码也有点乱。
[解决办法]
每次发送前最好对要发送的数据添加开始或结束标志。
接收时通过校验标志位来判断数据包