dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online MembersDevaraj T N
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » Code Snippets » Network

Building a Simple File download server using C#


Posted Date:     Category: Network    
Author: Member Level: Gold    Points: 10



 


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.


    Next Resource: Ping a computer and send file to remote host
    Previous Resource: Ping remote computer in the network
    Return to Resources
    Post New Resource
    Category: Network


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    (No tags found.)



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.