Hello there,

I'm not very professional in socket programming. I open a socket to the client and when connection succeed, I try to send a file. I read the file from the disk buffer by buffer and write this bytes on the NetworkStream object. Client receives this information from NetworkStream and writes them in a file on its own disk.
File transfers successfully, but during the sending operation, my CPU usage increases a lot and it takes a long time to do this operation. For example it takes about 4-5 minutes to send 1 MB file to client. But it not seems to be correct, because all of socket programs that I have seen are not as slow as my program.
What's the problem?
Thanks and sorry for my bad English!

Not sure, could you post some of your source code? Specifically portions that read and send the file, and also the portions that receive and write the file.

Hello there, sorry for my inacivity!

This is the client side code:

private void readFile(IAsyncResult ar)
        {
            nst = (NetworkStream)ar.AsyncState;
            string msg = "";
            int numberOfBytesRead = nst.EndRead(ar);
            foreach (byte b in readBuffer)
            {
                f.WriteByte(b);
            }
            msg = String.Concat(msg, Encoding.ASCII.GetString(readBuffer, 0, numberOfBytesRead));
            FileBuffer += msg;
            if (FileBuffer.IndexOf("***End of file***") == -1)
            {
                f.Close();
            }
            else
            {
                nst.BeginRead(readBuffer, 0, 1024, new AsyncCallback(readFile), nst);
            }
        }

and the server side:

public void SendFile(string path)
        {
            FileStream fs = File.OpenRead(path);
            byte[] fbuff = new byte[1024];

            while (fs.CanRead)
            {
                int bRead = fs.Read(fbuff, 0, fbuff.Length);
                nst.Write(fbuff, 0, (int)bRead);
            }

            /*for (int i = 0; i < file.Length; i++)
            {
                WriteByte(file[i]);
            }*/
            writeString("***End of file***");
        }

Thanks for your help, freinds!

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Since you failed to use CODE tags around your code, it's hard to refer to specific lines (and the formatting of the code sucks).

In your server routine, you use the construct while(fs.CanRead) . If the file is readable, this should never become false, thus you have an infinite loop of attempted file reads and network sendings. This will drive your CPU crazy. You should be checking if fs.Read(...) return zero, which means the end of the file has been reached.

Edited 5 Years Ago by Momerath: n/a

Thaks for your answer. My problem solved. God Bless you!

This article has been dead for over six months. Start a new discussion instead.