Hi,
I'm trying to send a file over socket from server to client ( im using Reverse Connection method )
So here is my steps:
0-send a upload request to client
1-reading file lenght + filename
2-send details to client
3-client will create a byte array with the calculated length
3-reading file from server into byte array
4-send byte with socket.send(byte,0,byte.lenght,socketflag.none)
But the problem is when i receive the "File Received" from the client, my file is broken.
How can i fix this?
What I have tried:
The ReceiveInfo() method is for client-side
static private void ReceiveInfo()
{
byte[] buffer = new byte[1024];
int received = 0;
try
{
received = ClientSocket.Receive(buffer);
}
catch (SocketException)
{
}
if (received == 0)
return;
byte[] data = new byte[received];
System.Array.Copy(buffer, data, received);
if(IsDownload)
{
DownloadCommand(data);
}
else
{
NormalCommand(data);
}
}
when i send the upload request,the flag of IsDownload will change to true.
Here is the step 3: (when client recevies the download request)
string[] info =
FileName = info[1];
FileSize = int.Parse(info[2]);
FileBytes = new byte[FileSize];
IsDownload = true;
Client receives the info,create byte array and waiting for server to send the data.
public static void DownloadCommand(byte[] data)
{
Buffer.BlockCopy(data, 0, FileBytes, WriteSize, data.Length);
WriteSize += data.Length;
if (FileBytes.Length == FileSize)
{
try
{
using (FileStream fs = File.Create(FileName))
{
byte[] info = FileBytes;
fs.Write(info, 0, info.Length);
}
Array.Clear(FileBytes, 0, FileBytes.Length);
}
catch (Exception ex)
{
}
SendData("File Received.");
IsDownload = false;
WriteSize = 0;
}
}
And here is the server codes:
public static void SendFile(Socket s, string fileName)
{
try
{
if (s.Connected)
{
TargetClient = s;
byte[] dataToSend = File.ReadAllBytes(fileName);
string fileInfo = Path.GetFileName(fileName) + "~" + dataToSend.Length;
SendCommand("IsDownload~" + fileInfo);
TargetClient.Send(dataToSend,0,dataToSend.Length,SocketFlags.None);
}
}
catch (Exception ex)
{
LogManager.SetLog("Error in SendFile(Socket,string):\n" + ex.Message);
};
}