发送函数如下,在发送少量数据没有问题,发送大量数据(也不是很多1K吧)出问题,还是在执行 ns.WriteByte(size[i]),还是在第四个循环出错,之前写成ns.Wrtit(size,0,4)也是出错,弹出提示“receive error:指定的参数已超出有效值得范围 参数 size”,不知是什么原因,关键是只是写4个字节,还没传数据呢。求高手解
public void Send(NetworkStream ns, byte[] sd)
{
try
{
byte[] size = BitConverter.GetBytes(sd.Length);
int sizeofsd = size.Length;
for (int i = 0; i < 4; i++)
{
ns.WriteByte(size[i]);
}
sizeofsd=sd.Length;
int writed = 0;
byte[] data = new byte[1024];
while (sizeofsd > 0)
{
if (sizeofsd >= 1024)
{
Buffer.BlockCopy(sd, 0, data, writed, 1024);
ns.Write(data, 0, 1024);
sizeofsd -= 1024;
writed += 1024;
}
else
{
Buffer.BlockCopy(sd, 0, data, writed, sizeofsd-writed);
ns.Write(data, 0, sizeofsd - writed);
}
}
}
catch (Exception ce)
{
throw new Exception("发送数据错误" + ce.ToString());
}
}C# 异常
public void Send(NetworkStream ns, byte[] sd)
{
try
{
byte[] size = BitConverter.GetBytes(sd.Length);
int sizeofsd = size.Length;
for (int i = 0; i < 4; i++)
{
ns.WriteByte(size[i]);
}
sizeofsd=sd.Length;
int writed = 0;
byte[] data = new byte[1024];
while (sizeofsd > 0)
{
if (sizeofsd >= 1024)
{
Buffer.BlockCopy(sd, 0, data, writed, 1024);
ns.Write(data, 0, 1024);
sizeofsd -= 1024;
writed += 1024;
}
else
{
Buffer.BlockCopy(sd, 0, data, writed, sizeofsd-writed);
ns.Write(data, 0, sizeofsd - writed);
}
}
}
catch (Exception ce)
{
throw new Exception("发送数据错误" + ce.ToString());
}
}C# 异常
直接
byte[] data = new byte[sd.Length + sizeof(int)];
Buffer.BlockCopy(BitConverter.GetBytes(sd.Length), 0, data, 0, sizeof(int));
Buffer.BlockCopy(sd, 0, data, sizeof(int), sd.Length);
ns.Write(data, 0, data.Length);
{
try
{
// 先发送4个字节总长度
byte[] size = BitConverter.GetBytes(sd.Length);
ns.Write(size, 0, size.Length); // 总长度
int sizeofsd = sd.Length; // 当前索引
int writed = 0; // 需要发送的长度
int sendlen = 0;
if (sizeofsd >= 1024)
{
// 如果总长度大于1K,则分包发送
while (sizeofsd > 0)
{
// 判断剩余长度
sendlen = sizeofsd > 1024 ? 1024 : sizeofsd; ns.Write(sd, writed, sendlen); sizeofsd -= 1024;
writed += 1024;
}
}
else
{
// 总长度小于1K,直接发送
ns.Write(sd, 0, sizeofsd);
}
}
catch (Exception ce)
{
throw new Exception("发送数据错误" + ce.ToString());
}
}