首页 > Windows开发 > 详细

C#Socket文件传输(发送与接收代码)

时间:2021-02-20 16:08:21      阅读:35      评论:0      收藏:0      [点我收藏+]

这里是发送的代码:SendVarData是转码后发送函数

技术分享图片
/// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="userName"></param>
        private void SendFileToClient(string userName)
        {
            User targetUser = userListDict[userName];
            String targetUserIP = "127.0.0.1";

            FileInfo EzoneFile = new FileInfo(sendFilePath);
            FileStream EzoneStream = EzoneFile.OpenRead();
            //包的大小
            int packetSize = 1000;
            //包的数量
            int packetCount = (int)(EzoneFile.Length / ((long)packetSize));

            //最后一个包的大小
            int lastPacketData = (int)(EzoneFile.Length-((long)packetSize*packetCount));

            byte[] data = new byte[packetSize];



            try
            {
                IPHostEntry ipHost = Dns.GetHostEntry(targetUserIP);
                IPAddress ipAdd = ipHost.AddressList[0];
                IPEndPoint ipEndP = new IPEndPoint(ipAdd, targetUser.userPort);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(ipEndP);
                //发送本机昵称
                FormClient.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(localNickName));
                //发送包的大小
                FormClient.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(packetSize.ToString()));
                //发送包的总数量
                FormClient.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(packetCount.ToString()));
                //client.SendFile(sendFilePath);
                for (int i = 0; i < packetCount;i++ )
                {
                    EzoneStream.Read(data, 0, data.Length);
                    FormClient.SendVarData(client,data);
                    AddReceiveFileInfo(userDialogDict[userName], packetCount.ToString() + "/" + i.ToString());
                }
                if (lastPacketData!=0)
                {
                    data=new byte[lastPacketData];
                    EzoneStream.Read(data, 0, data.Length);
                    FormClient.SendVarData(client, data);
                }
                AddReceiveFileInfo(userDialogDict[userName], "传输完成!");

                client.Shutdown(SocketShutdown.Both);
                client.Close();

            }
            catch (System.Exception ex)
            {

            }
        }
        public static int SendVarData(Socket s, byte[] data)
        {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;
            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);

            while (total < size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }

            return total;
        }
View Code

以下是接收代码:

ReceiveVarData是接收后转码
技术分享图片
/// <summary>
        /// 接受其他客户端的文件
        /// </summary>
        private void ReceiveClientFile()
        {
            while (true)
            {

                Socket clientsocket = serverSocket.Accept();
                Thread receiveThread = new Thread(ReceiveClientFileData);
                receiveThread.Start(clientsocket);
                receiveThread.IsBackground = true;
            }

        }

        private void ReceiveClientFileData(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            string totalSize;//文件大小
            int totalCount = 0;//总的包数量
            int receiveCount = 0;//统计已收的包的数量
            string sendClientName;

            if (File.Exists(receiveFilePath))
            {
                File.Delete(receiveFilePath);
            }

            FileStream fs = new FileStream(receiveFilePath, FileMode.Create,FileAccess.Write);
            //发送端的用户名字,用于确定对话框
            sendClientName = System.Text.Encoding.Unicode.GetString(FormClient.ReceiveVarData(myClientSocket));
            //文件大小
            totalSize = System.Text.Encoding.Unicode.GetString(FormClient.ReceiveVarData(myClientSocket));
            //总的包数量
            totalCount = int.Parse(System.Text.Encoding.Unicode.GetString(FormClient.ReceiveVarData(myClientSocket)));

            AddReceiveFileInfo(userDialogDict[sendClientName],receiveCount + "/" + totalSize);
            while (true)
            {
                byte[] data = FormClient.ReceiveVarData(myClientSocket);
                //接收来自socket的数据

                if (data.Length==0)
                {
                    AddReceiveFileInfo(userDialogDict[sendClientName], "接收完成!");
                    fs.Write(data, 0, data.Length);
                    break;
                }
                else
                {
                    receiveCount++;
                    AddReceiveFileInfo(userDialogDict[sendClientName], receiveCount + "/" + totalSize);
                    fs.Write(data,0,data.Length);
                }


            }
            fs.Close();
            myClientSocket.Close();

        }

        private static byte[] ReceiveVarData(Socket s)
       {
           int total = 0;
           int recv;
           byte[] datasize = new byte[4];
           recv = s.Receive(datasize, 0, 4, SocketFlags.None);
           int size = BitConverter.ToInt32(datasize, 0);
           int dataleft = size;
           byte[] data = new byte[size];
           while (total < size)
           {
               recv = s.Receive(data, total, dataleft, SocketFlags.None);
               if (recv == 0)
               {
                   data = null;
                   break;
               }
               total += recv;
               dataleft -= recv;
           }
           return data;
       }
View Code

C#Socket文件传输(发送与接收代码)

原文:https://www.cnblogs.com/jickcap/p/14421390.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!