Saturday, October 20, 2012

Send File from Server to Client using C# Socket Programming 4/6



6) Client Action: This section of code is retrieving file name length and by using this file name which was sent by server at the starting of file data. This will require retrieving file name.


int fileNameLen = BitConverter.ToInt32(clientData, 0);

string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);


7) Client Action: Now received data is saving at client side by using below lines of code with the help of binary stream writer.


BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append));

bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);


Here file data is starting to retrieve after file size and file name bytes. This has managed in 2nd line.


By that way one small file can be sent from server to client.


8) Client and Server Action: Now server and client both will do same activity; that is to release server and client socket by using close method of socket. Client needs to close binary stream writer as well.


So by following these steps a file can be sent from server to client. Same way we can send large file from server to client. TCP buffer can not handle large data size at a time. So if you try to send large file it will throw overflow error. To avoid this error you need to slice big file in small pieces (same thing has applied in 2GB file transfer article) and need to send one by one slice. So there will be loop to send file from server to client that means step 5 to step 7 will repeat.


Also server can send some particular file based on client request. But for that client need to send file name at the time of server request. So server can search file based on this information, so can read and send particular file to client.


By handling multiple clients objects one server can send file to multiple clients simultaneously but for that you need to create multithread application and need to keep track client socket object array with data file. So programming must be more complex. I am planning to write codes up to multiple client to client large file transfer with the help of one server application step by step. So keep watching my blog to learn new things.


Download this project from below link:

https://rapidshare.com/files/691859425/Client and Server - Send Small File from Server to Client.zip  



1 comment:

Unknown said...

Very Good! Thanks for your help!