日期:2014-05-17  浏览次数:21099 次

c# socket如何传输大数据
我服务端通过SOCKET向客户端发送大数据(M以上的数据),数据大后,容易掉包,用多线程的话不掉包,但是速度又比较慢了。

请教各位大神了!

------解决方案--------------------
<code C#>
const int blockLength=512*1024;
public void SendFile(string filePath, NetworkStream stream) //发送文件
{
//传输内容
using (FileStream fs = File.Open(filePath, FileMode.Open))
{
int readLength = 0;
byte[] data = new byte[blockLength];

//发送大小
byte[] length = new byte[8];
BitConverter.GetBytes(new FileInfo(filePath).Length).CopyTo(length, 0);
stream.Write(length, 0, 8);

//发送文件
while ((readLength = fs.Read(data, 0, blockLength)) > 0)
{
stream.Write(data, 0, readLength);
}
}

}

public bool ReceiveFile(string fileName, NetworkStream stream) //接收文件
{
try
{
long count = GetSize(stream);
if (count == 0)
{
return false;
}
long index = 0;
int currentBlockLength = 0;
int receivedBytesLen = 1;
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
while (receivedBytesLen > 0 && index < count)
{
byte[] clientData = new byte[blockLength];
receivedBytesLen = 0;

if (blockLength < count - index)
{
currentBlockLength = blockLength;
}
else
{
currentBlockLength = (int)(count - index);
}
receivedBytesLen = stream.Read(clientData, 0, currentBlockLength);
fs.Write(clientData, 0, receivedBytesLen);
index += receivedBytesLen;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}

private int GetSize(NetworkStream stream) //获取文件大小
{
int count = 0;
byte[] countBytes = new byte[8];
try
{
if (stream.Read(countBytes, 0, 8) == 8)
{
count = BitConverter.ToInt32(countBytes, 0);
}
else
{
return 0;
}
}
catch
{
return 0;
}
return count;
}
</code>