Click here to Skip to main content
15,915,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have set up a server, and am trying to send a file to a client. The issue I'm having is that the file received on the client is sometimes either smaller, or bigger than the original file.

Here is the code I'm using:

Server:

C#
class FileSendServer
    {
        Thread t1;
        byte[] clientData;

        public FileSendServer()
        {

        }

        public void letsGo()
        {
            t1 = new Thread(new ThreadStart(StartListening));
            t1.Start();
        }

        public void setFileLoc(string floc)
        {
            string filePath = "";
            string fileName = floc;
            /* File reading operation. */
            fileName = fileName.Replace("\\", "/");
            while (fileName.IndexOf("/") > -1)
            {
                filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
                fileName = fileName.Substring(fileName.IndexOf("/") + 1);
            }


            byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);

            byte[] fileData = File.ReadAllBytes(filePath + fileName);

            /* Read & store file byte data in byte array. */
            clientData = new byte[4 + fileNameByte.Length + fileData.Length];

            /* clientData will store complete bytes which will store file name length, file name & file data. */
            byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
            /* File name length's binary data. */
            fileNameLen.CopyTo(clientData, 0);
            fileNameByte.CopyTo(clientData, 4);
            fileData.CopyTo(clientData, 4 + fileNameByte.Length);
            /* copy these bytes to a variable with format line [file name length][file name][ file content] */
        }

        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public void StartListening()
        {
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(ipEnd);
                listener.Listen(100);
                while (true)
                {
                    allDone.Reset();
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                    allDone.WaitOne();

                }
            }
            catch (Exception ex)
            {

            }

        }
        public void AcceptCallback(IAsyncResult ar)
        {
            allDone.Set();

            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            handler.Send(clientData);

            handler.Close();
        }
    }


Client:

C#
class FileReceiveClient
    {
        int flag = 0;
        string receivedPath = "";
        public delegate void MyDelegate();
        Form1 myForm1;

        public FileReceiveClient(Form1 x)
        {
            myForm1 = x;
            ReceiveFile();
        }

        public class StateObject
        {
            // Client socket.
            public Socket workSocket = null;

            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
        }

        public void ReceiveFile()
        {
            try
            {
                IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
                IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("192.168.1.104"), 9050);
                /* Make IP end point same as Server. */
                Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                /* Make a client socket to send data to server. */
                clientSock.Connect(ipEnd);

                StateObject state = new StateObject();
                state.workSocket = clientSock;
                clientSock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
                flag = 0;

            }
            catch (Exception ex)
            {

            }

        }

        public void ReadCallback(IAsyncResult ar)
        {
            int fileNameLen = 1;
            String content = String.Empty;
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;
            int bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {

                if (flag == 0)
                {
                    fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                    string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                    receivedPath = "C:/RBParty/Songs/" + fileName;
                    myForm1.fileLoc = receivedPath;
                    flag++;
                }

                if (flag >= 1)
                {
                    try
                    {
                        BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                        if (flag == 1)
                        {
                            writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                            flag++;
                        }
                        else
                            writer.Write(state.buffer, 0, bytesRead);
                        writer.Close();
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }

                    catch (Exception ee)
                    {

                    }
                }

            }

            else
            {
                Thread.CurrentThread.Abort();
            }

        }
    }


Any help is appreciated. Thank you in advance.
Posted
Comments
LanFanNinja 19-Nov-11 3:04am    
Check solution below.

Try using my article instead : WCF Killer[^]
 
Share this answer
 
Ok so I created a WinForms app to test out your code and at first was having the same problems you are having until I realized you are calling ReceiveFile(); in your FileReceiveClient class constructor. You see I was also calling this from my main form after I created an instance of the FileReceiveClient class. Once I realized this I ran the code several more times with no problems. So my suggestions are (1) make sure you are not calling ReceiveFile() more than once like I was. (2) Make sure you are verifying the file size by looking at the size and size on disk values in the files properties dialog (bring it up by right clicking the file and choosing properties). Hope you figure it out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900