Socket.Receive()返回不正确的数据量

时间:2012-06-08 22:44:39

标签: c# file sockets upload send

作为学校项目我正在创建一个FileSharing应用程序。 我将所有想要的消息发送到服务器,一切都很好,但是当涉及到将文件上传到服务器时,文件永远不会是它应该的样子。我调试了应用程序,发现Socket没有返回正确的字节数。 我不知道这是不是正确的方式,但我认为这是错的。 例如,当我上传一个小的.txt文件,然后用Notepad ++打开它时,我会在文件的末尾看到很多null,这意味着我写的更多,然后应该写。我在互联网上搜索了它,并在codeplex上找到了一个与我正在做的相同的应用程序,但套接字返回了正确的数据量http://srf.codeplex.com/

如果有人能帮助我,我将不胜感激。 对不起,如果英语很糟糕,那不是我的母语。

处理第一条消息并接收clint连接的服务器函数:

    public void Brodcast()
    {
        tcpListener.Start();
        while (true)
        {
            try
            {
                ClientSocket = tcpListener.AcceptSocket();
                MessageReceiving();
            }
            catch { }
        }
    }

    public void MessageReceiving()
    {
        if (ClientSocket.Connected)
        {
            OpenPackage.MessageTypeToBytes RSMessage = new OpenPackage.MessageTypeToBytes();
            ClientSocket.Receive(RSMessage.MessageBytes, 512, SocketFlags.None);
            if (RSMessage.TypeOfMessage == MessageType.Login)
                DoLogin();
            else if (RSMessage.TypeOfMessage == MessageType.Download)
                SendFile();
            else if (RSMessage.TypeOfMessage == MessageType.Upload)
                ReceiveFile();
            else if (RSMessage.TypeOfMessage == MessageType.NConta)
                NewAccount();
            else if (RSMessage.TypeOfMessage == MessageType.Search)
                SearchResult();
            else if (RSMessage.TypeOfMessage == MessageType.Apagar)
                DeleteFile();
        }
    }

服务器:

    public void ReceiveFile()
    {
        try
        {
            byte[] MessageBytes = new byte[512];
            ClientSocket.Receive(MessageBytes, 512, SocketFlags.None);
            string Nickname = Encoding.ASCII.GetString(MessageBytes);
            string[] CNickFich = Nickname.Split('$');
            FileHandler Handler = new FileHandler();
            long DirectorySize = Handler.GetDirectorySize("C:\\" + CNickFich[0]);
            long FileSize = long.Parse(CNickFich[2]);
            bool Subs = false;
            if ((FileSize + DirectorySize) < MaxFolderSize && MaxFileSize > FileSize)
            {
                if (!Directory.Exists("C:\\" + CNickFich[0]))
                    Directory.CreateDirectory("C:\\" + CNickFich[0]);
                if (File.Exists("C:\\" + CNickFich[0] + "\\" + CNickFich[1]))
                {
                    File.Delete("C:\\" + CNickFich[0] + "\\" + CNickFich[1]);
                    Subs = true;
                }
                MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.OK };
                ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);

                int qtdReceived = 0;
                long CurrentSize = 0;
                byte[] FileBuffer = new byte[BufferSize];
                FileStream FileStr = new FileStream("C:\\" + CNickFich[0] + "\\" + CNickFich[1], FileMode.CreateNew, FileAccess.Write);
                BufferedStream BufferStr = new BufferedStream(FileStr);
                while (CurrentSize < FileSize)
                {
                    qtdReceived = ClientSocket.Receive(FileBuffer, 0, FileBuffer.Length, 0);
                    CurrentSize += qtdReceived;
                    BufferStr.Write(FileBuffer, 0, qtdReceived);
                    BufferStr.Flush();
                }
                BufferStr.Close();
                FileStr.Close();
                SqlDataAdapter data = new SqlDataAdapter("SELECT COD_CONTA FROM CONTAS WHERE NICKNAME='"
                + CNickFich[0] + "'", OConn);
                DataTable dt = new DataTable();
                data.Fill(dt);
                if (NFicheiro(Handler.MD5HashFromFile("C:\\" + CNickFich[0] + "\\" + CNickFich[1]), "C:\\" + CNickFich[0] + "\\" + CNickFich[1], Subs,
                    int.Parse(dt.Rows[0][0].ToString()), CNickFich[3]))
                    MessageInBytes.TypeOfMessage = MessageType.OK;
                else
                    MessageInBytes.TypeOfMessage = MessageType.Erro;
                ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
                //NFicheiro(new FileHandler().MD5HashFromFile("C:\\" + CNickFich[0] + "\\" + CNickFich[1]), "C:\\" + CNickFich[0], false, 1, );
            }
            else
            {
                MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
                ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
            }
        }
        catch
        {
            MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
            ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
        }
    }

客户端:

    private void UploadWork_DoWork(object sender, DoWorkEventArgs e)
    {
        FileStream FileStr = null;
        BufferedStream BufferStr = null;
        Stopwatch Counter = new Stopwatch();
        try
        {
            int CurrentProgress = 0;
            Program.CTasks.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Program.CTasks.ClientSocket.ReceiveTimeout = 60000;
            Program.CTasks.ClientSocket.SendTimeout = 60000;
            Program.CTasks.ClientSocket.Connect(IPAddress.Parse(Program.CTasks.HostName), Program.CTasks.Port);
            MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Upload };
            Program.CTasks.ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
            FileInfo FileNFO = new FileInfo(Open.FileName);
            byte[] NickPath = new byte[512];
            byte[] UNickPath = Encoding.ASCII.GetBytes(Program.Nickname + "$" + Open.FileName.Substring(Open.FileName.LastIndexOf('\\') + 1) + "$" + FileNFO.Length.ToString() + "$");
            byte[] TagCollectionBytes = Encoding.ASCII.GetBytes(TagCollection + "$");
            UNickPath.CopyTo(NickPath, 0);
            TagCollectionBytes.CopyTo(NickPath, UNickPath.Length);
            Program.CTasks.ClientSocket.Send(NickPath, 512, SocketFlags.None);
            Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
            if (MessageInBytes.TypeOfMessage == MessageType.OK)
            {
                long FileSize = FileNFO.Length;
                long CurrentFileSize = 0;
                long qtdRead = 0;
                byte[] FileBytes = new byte[BufferSizer];
                FileStr = new FileStream(Open.FileName, FileMode.Open, FileAccess.Read);
                BufferStr = new BufferedStream(FileStr);
                Counter.Start();
                while ((qtdRead = BufferStr.Read(FileBytes, 0, FileBytes.Length)) > 0)
                {
                    Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
                    CurrentFileSize += qtdRead;
                    CurrentProgress = (int)((CurrentFileSize * 100) / FileSize);
                    UploadSpeed = ((double)CurrentFileSize / (Counter.Elapsed.TotalMilliseconds / 100));
                    UploadWork.ReportProgress(CurrentProgress);
                }
                FileStr.Close();
                Counter.Stop();
                Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
                Program.CTasks.ClientSocket.Close();
            }
        }
        catch
        {
            try
            {
                Counter.Stop();
                FileStr.Close();
                Program.CTasks.ClientSocket.Close();
            }
            catch { }
        }
    }

2 个答案:

答案 0 :(得分:2)

您发送的数据过多......文件末尾FileBytes将会更长时间完全填满,您应该只发送qtdRead个字节。

替换

Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);

使用

Program.CTasks.ClientSocket.Send(FileBytes, 0, qtdRead, 0);

答案 1 :(得分:1)

您使用的是缓冲区长度,而不是发送时读取的长度。