这里是发送的代码: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
posted on 2021-02-20 15:22  小杰杰儿  阅读(469)  评论(0编辑  收藏  举报