Sending files over the network with .NET
Griffin.Framework has built in support for streams if you are using MicroMsg. This example will demonstrate how you can send a file stream over the network.
Install the nuget package “griffin.framework” and create a console application with the following code:
class Program
{
static void Main(string[] args)
{
var server = new ChannelTcpListener();
server.MessageReceived = OnServerReceivedMessage;
server.Start(IPAddress.Any, 0);
var client = new ChannelTcpClient<object>(
// data contract will be used for plain .NET objects
new MicroMessageEncoder(new DataContractMessageSerializer()),
new MicroMessageDecoder(new DataContractMessageSerializer())
);
client.ConnectAsync(IPAddress.Loopback, server.LocalPort);
client.SendAsync(new FileStream("TextSample.txt", FileMode.Open)).Wait();
Console.ReadLine();
}
private static void OnServerReceivedMessage(ITcpChannel channel, object message)
{
var file = (Stream)message;
var reader = new StreamReader(file);
var fileContents = reader.ReadToEnd();
Console.WriteLine(fileContents);
}
}
The library can send/receive any type of stream of any size (as long as the size is known). The client will automatically create a MemoryStream or FileStream depending on the stream size. So it doesn’t matter if the stream is 4Gb or 2Kb.