Resources » Code Snippets » Network

Building a Simple File download server using C#


Posted Date: 27-Mar-2007  Last Updated:   Category: Network    
Author: Member Level: Gold    Points: 10


This article explains about Building a Simple File download server using C# and simple FileServer class which acts as a file download server for clients. A parallel Client class is also presented which asks for the file download at a specified location.



The .NET framework provides two namespaces, System.Net and System.Net.Sockets for network programming. The classes and methods of these namespaces help us to write programs, which can communicate across the network. The most widely used protocol TCP is used for stream-based communication. The System.Net.Sockets.Socket is an important class from the System.Net.Sockets namespace. A Socket instance has a local and a remote end-point associated with it. The local end-point contains the connection information for the current socket instance. To create a network server for TCP/IP streaming, you start by creating a TcpListener object to listen to the TCP/IP port you've chosen. On the client side; the client would instantiate a TcpClient class, which represents a TCP/IP client connection to a host.

Demonstrated here is a simple FileServer class which acts as a file download server for clients. A parallel Client class is also presented which asks for the file download at a specified location. Basically; the server reads out the file content using a FileStream object and writes the content out to the Socket using a NetworkStream. The client reads out from the Socket and writes the content out to a FileStream connected to a local file on its side. The communication between the server and client is synchronous. For simplicity; the server is made to handle one request at a time. Also the FileServer always gives the same file to it's clients (hardcoded).

//the Server class
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class FileServer
{
static string hostName = "127.0.0.1";
static int port = 65000; //if this port is not available on your machine; pick up some other
IPAddress localAddr = IPAddress.Parse(hostName);

public void Start()
{
TcpListener tcpListner = new TcpListener(localAddr, port);
tcpListner.Start(); //start listening to client request
for (; ; ) //infinite loop
{
//blocks until a client request comes
Socket socket = tcpListner.AcceptSocket();
if (socket.Connected)
{
//Delegate to the SendFileToClient method
SendFileToClient(socket);
socket.Close();
}
}
}

void SendFileToClient(Socket socket)
{
NetworkStream netStream = new NetworkStream(socket);
StreamWriter writer = new StreamWriter(netStream);
//make sure the specified file exists on your server machine
FileStream fileStream = File.Open(@"D:\csharp.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader reader = new StreamReader(fileStream);
string strReadLine = null;
do
{
strReadLine = reader.ReadLine();
if(strReadLine!= null) writer.WriteLine(strReadLine);
writer.Flush(); //make sure content is flushed and reaches the client
} while (strReadLine != null); //exit when nothing more to read
writer.Close();
}
}

//the Client class
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class Client
{
//modify the host name if you are running the server in a different machine
static string hostName = "127.0.0.1";
static int port = 65000;

public void FetchFileFromServer()
{
TcpClient client = new TcpClient(hostName, port);
if (client.Connected)
{
NetworkStream netStream = client.GetStream();
StreamReader reader = new StreamReader(netStream);
string strReadLine = null;
//note: make sure that the file location/ name is different than the server's location
//if you are running the server and client on the same machine
FileStream fileStream =
File.Open(@"C:\csharp.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
StreamWriter writer = new StreamWriter(fileStream);
do
{
strReadLine = reader.ReadLine();
if (strReadLine != null)
writer.WriteLine(strReadLine);
} while (strReadLine != null); //exit when there is nothing to receive
writer.Close();
netStream.Close();
}
}
}

Here is some test code if you want to run the Server and client on the same machine:

new Thread(new ThreadStart(new FileServer().Start)).Start();
Thread client = new Thread(new ThreadStart(new Client().FetchFileFromServer));
client.Start();
client.Join();
//the Server Thread keeps running

If you run the above code you will have a copy of the file csharp.txt in D: drive "downloaded" to the C: drive.


Did you like this resource? Share it with your friends and show your love!

Responses to "Building a Simple File download server using C#"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Phagu Mahato
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India