C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Building a Simple File download server using C#


Posted Date: 27 Mar 2007    Resource Type: Code Snippets    Category: Network

Posted By: Prajnan Das       Member Level: Gold
Rating:     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.




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Ping a computer and send file to remote host
Previous Resource: Ping remote computer in the network
Return to Discussion Resource Index
Post New Resource
Category: Network


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

audio conferencing services

Contact Us    Privacy Policy    Terms Of Use