Thread: File transfer- the file sometimes not full transferred

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #9
    Registered User valaris's Avatar
    Join Date
    Jun 2008
    Location
    RING 0
    Posts
    507
    Here is a routine you can use to build the packet that the client will send to the server. The first sizeof(int) bytes will contain the length of the file in bytes that you are sending. Immediately after those bytes will begin the actual file data. Now since TCP is a byte stream protocol, and it guarantees that the bytes you send will arrive in order, on the server side we can peek until there are sizeof(int) bytes in the receive buffer. Once we have those bytes we know the length of the file. After that we can just call some other routine to block on a read of the socket until it reads those total number of bytes from the stream. After that simply return your array of bytes and use it for whatever you want on the server.

    Code:
            static byte[] GetFileBuffer(string FileName)
            {
                if (!File.Exists(FileName))
                    throw new FileNotFoundException("Could Not Find " + FileName);
    
                using (MemoryStream ms = new MemoryStream())
                {
                    using (BinaryWriter br = new BinaryWriter(ms))
                    {
                        FileInfo Info = new FileInfo(FileName);
                        br.Write((int)Info.Length);
                        br.Write(File.ReadAllBytes(FileName));
    
                        //The stream expands as you add bytes, make sure the final buffer
                        //is the specified size.
                        ms.Capacity = (int)Info.Length + sizeof(int);
                        return ms.GetBuffer();
                    }
                }
            }
    Note the using blocks are just syntactic sugar for calling the dispose method from the IDispose interfaces that those classes implement. This insures that any resources that the objects used will be disposed of (and in many cases also surpresses the GC from performing a finalize on the object for extra efficiency).
    Last edited by valaris; 02-20-2009 at 12:19 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM