Monday, August 17, 2009

File Transfer between Client and Server

Sender’s Code

Write the following using statements if they are not initially written:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

Now write the following function/code (tried and tested in a console application) :

try
{
IPAddress ipAddress = IPAddress.Parse(” /* IP Address of receiver */ “);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, 8001);
Socket clientSock = new Socket(AddressFamily.InterNetwork,

SocketType.Stream, ProtocolType.IP);

string fileName = ” /* Name Of File */ “;

// Write the name of the file along with its extension above
string filePath = @” /* Path Of File */ “;

// Write the path of the file here e.g “D:/Projects”


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);

clientSock.Connect(ipEnd);
Console.WriteLine(”Sending File {0}”, fileName);
clientSock.Send(clientData);
// The file has been sent


clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(”File Sending fail.” + ex.Message);
Console.ReadLine();
}

———————————————————————————————————————————————————————-

Receiver’s Code

Write the following using statements if they are not initially written:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Collections.Generic;

Now write the following function/code (tried and tested in a console application) :

try
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 8001);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(8001);
Socket clientSock = sock.Accept();

byte[] clientData = new byte[1024 * 5000];
string receivedPath = “”;

int receivedBytesLen = clientSock.Receive(clientData);

int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen – 4 – fileNameLen);

// The file has been received

bWrite.Close();
clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(”File Receiving fail.” + ex.Message);
Console.ReadLine();
}

No comments:

Post a Comment