c#socket怎么传输大数据

 我来答
就烦条0o
推荐于2018-03-23 · 知道合伙人软件行家
就烦条0o
知道合伙人软件行家
采纳数:33315 获赞数:46492
从事多年系统运维,喜欢编写各种小程序和脚本。

向TA提问 私信TA
展开全部
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;
        }
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式