I have a client application, and a server one.
I want to send a file from one machine to the other, so it seems the socket.FileSend method is exactly what I'm looking for.
But since there isn't a FileReceive method what should I do on the server side in order to receive a file? (My problem is because the file will have a variable size, and will be bigger than any buffer I can create GB order...)
On the server side you could use a TcpListener and once a client is connected read the stream in chunks and save it to a file:
class Program
{
static void Main()
{
var listener = new TcpListener(IPAddress.Loopback, 11000);
listener.Start();
while (true)
{
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var output = File.Create("result.dat"))
{
Console.WriteLine("Client connected. Starting to receive the file");
// read the file in chunks of 1KB
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
}
As far as the sending is concerned you may take a look at the example provided in the documentation of the SendFile method.
This being said you might also take a look at a more robust solution which is to use WCF. There are protocols such as MTOM which are specifically optimized for sending binary data over HTTP. It is a much more robust solution compared to relying on sockets which are very low level. You will have to handle things like filenames, presumably metadata, ... things that are already taken into account in existing protocols.
You need use Socket.Receive or Socket.BeginReceive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With