Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8044759
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T05:19:39+00:00 2026-06-05T05:19:39+00:00

As school project I’m creating a FileSharing application. I send all the messages I

  • 0

As school project I’m creating a FileSharing application.
I send all the messages I want to the server and everything is fine, but when it comes to Upload a file to the server, the file is never the way it should be. I debugged the application and discovered that the Socket is not returning the correct amount of bytes.
I don’t know if that’s the correct way it should be, but I thinks it’s wrong.
For example when I upload a small .txt file, and open it with Notepad++ I see a lot of null’s at the end of the file, wich means that I’m writting more then it should be written. I searched it on the internet and found an application at codeplex that does the same that I’m doing, but the socket returns the correct amount of data, http://srf.codeplex.com/.

I would appreciate if someone could help me.
Sorry if english sucks, its not my native language.

Server function that handles first message and does receives the clint connection:

    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();
        }
    }

Server:

    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);
        }
    }

Client:

    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 { }
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T05:19:40+00:00Added an answer on June 5, 2026 at 5:19 am

    You’re sending too much data… at the end of the file FileBytes will on longer be completely full, and you should only send qtdRead bytes.

    Replace

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

    With

    Program.CTasks.ClientSocket.Send(FileBytes, 0, qtdRead, 0);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a school project, for which I want to develop a web application
I'm working on a school project with a server application that holds centralized data,
I'm creating a backbone for a school project, but I'm running into unresolved external
I have a school project in which I have to implement a chat application,
I'm doing a school project about maintaining a personal Database. but my tutors didn't
I'm nearing the end of a school project with programming in Xcode, but right
greeting all i am working on school project and i have a problem with
For a school project, I'm building an application using PreferenceScreen s as a framework.
Im working in a school project. I want the user to select categories to
I have multiple python files for a school project that I want to open

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.