Search code examples
c#filesocketstransfer

Transfer file with socket but program (not responding) when transfer data c#


I try to type a single program have (client) and (multi-client server) to send and receive files The transfer is totally successfully but the program (Not responding) when it transfer data and return normaly when it finish

You can download the project with link: http://www.mediafire.com/?81gs1zqbsgqldwb

please help me how to fix (Not responding) when the program transfer data ???

The send mechanism :

byte[] buffer = new byte[packetSize];
while (sum < length)
{
    if (length - sum > packetSize)
    {
        count = fileStream.Read(buffer, 0, packetSize);
        Send(socket_File, buffer);
    }
    else
    {
        buffer = new byte[length - sum];
        count = fileStream.Read(buffer, 0, length - sum);
        Send(socket_File, buffer);  
    }
    sum = sum + count;
}
fileStream.Close();

The receive mechanism :

string path = Save_File.FileName;
FileInfo fi = new FileInfo(path);
FileStream fs = fi.OpenWrite();
byte[] buffer = new byte[packetSize];

while (sum < File_Size)
{
    if (File_Size - sum > packetSize)
    {
        count = Socket_File_Client.Receive(buffer, 0, packetSize, 0);
        fs.Write(buffer, 0, count);
    }
    else
    {
        buffer = new byte[File_Size - sum];
        count = Socket_File_Client.Receive(buffer, 0, File_Size - sum, 0);
        fs.Write(buffer, 0, count);
    }
    sum = sum + count;
}
fs.Close();

Solution

  • Regular IO as in your code is blocking. This means that the thread that is executing your code will have to wait until the transfer is completed. If this thread is the main thread in your program then it will cause your program to be unresponsive to user input ("Not Responding") until it is finished.

    You have two ways to make your program responsive while doing blocking IO:

    • Use asynchronous IO
    • Run your transfer in another thread

    I think the second option is probably easier in your case.

    Just use ThreadPool.QueueUserWorkItem or BackgroundWorker. See this article for explanations and details.