Saturday, October 20, 2012

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

4) Server Action: These codes are not directly related with socket programming. This is using to read and send file to client.

string fileName = "test.txt";// "Your File Name";

string filePath = @"C:\FT\";//Your File Path;

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

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

byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];

byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

fileNameLen.CopyTo(clientData, 0);

fileNameByte.CopyTo(clientData, 4);

fileData.CopyTo(clientData, 4 + fileNameByte.Length);

These lines of code reading some particular file from local drive and string its data in byte array “clientData”. File data need to store in array with raw byte format to send these to client. With data file name size string at initial of file data. This is predefined between client and server and it needs to do, otherwise client will not get file name which is sending by server.

For my case I am using first four byte to represent file name length and form 5th byte file name is storing. So all file data will store after file name.

5) Server Action: Now file data is in byte array and it needs to send to client. The same thing is happening by using below code with the help of client socket (clientSock) object, which was created during client request acceptance.


Basically server application task ends here for small file transfer. Remaining code has used for some decoration and socket closing related things.

5) Client Action: Now again turn comes to client and it will perform below tasks:

byte[] clientData = new byte[1024 * 5000];

string receivedPath = "C:/";

int receivedBytesLen = clientSock.Receive(clientData);

Here first two lines are just creating byte array to store server data and path is used to decide where data to be save. In my code, I am saving data in C: drive.

Last line is start receiving data from server. Whenever client socket starts receiving server data then it returns length of data which has captured in a integer variable.

No comments: