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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…