You are on page 1of 13

In The Name Of GOD

Introduction to
Network programming
in C#

Farid Bekran

Tabriz University
Tabriz – Iran
2010
system.net namespace
System.net name space contains the following classes:
1) WebClient
2) WebRequest & WebResponse
3) HttpListener
4) SmtpClient
5) Dns
6) TcpClient & UdpClient & TcpListener &
UdpListener
7) Socket
ip address and IPAddress class
IPv4 sample:101.102.103.104 32bits
IPv6 sample: [3EA0:FFFF:198A:E4A3:4FF2:54f-A:41BC:8D31] 128bits
Programming example:
IPAddress a1 = new IPAddress(new byte[] { 101, 102, 103, 104 });
IPAddress a2 = IPAddress.Parse("101.102.103.104");
IPAddress a3 = IPAddress.Parse("[3EA0:FFFF:198A:E4A3:4FF2:54fA:41BC:8D31]");

IPEndPoint manages the combination of ip address and port


IPAddress a = IPAddress.Parse("101.102.103.104");
IPEndPoint ep = new IPEndPoint(a, 222); // Port 222
Internet addresses and Uri class
The Uri class used for manage different aspects of internet addresses and
has no other special usage.

Uri info = new Uri("http://www.domain.com:80/info/");


Uri page = new Uri("http://www.domain.com/info/page.html");
Console.WriteLine(info.Host); // www.domain.com
Console.WriteLine(info.Port); // 80
Console.WriteLine(page.Port); // 80 (Uri knows the default HTTP port)
WebClient class
This class does the operations for the connectivity via http and ftp
protocols. Unlike WebRequest and WebResponse classes that only
work with stream’s, this class can work with stream’s string’s byte
array’s and file’s.

Example: download a html file from a server. And save it next to exe file
using (WebClient wc = new WebClient())
{
wc.Proxy = null;
wc.DownloadFile("http://www.farid.com/codes/code.html","code.html");
}
System.Diagnostics.Process.Start("code.html");
WebRequest & WebResponse
These classes are more complex than Webclient but more flexible
than WebClient

Example: download a html file and open it by a browser.


WebRequest req = WebRequest.Create("http://www.farid.com/codes/code.html");
req.Proxy = null;
using (WebResponse res = req.GetResponse())
using (Stream s = res.GetResponseStream())
using (StreamReader sr = new StreamReader(s))
File.WriteAllText ("code.html", sr.ReadToEnd ());
System.Diagnostics.Process.Start ("code.html");
What is difference between above code and below?
using (WebClient wc = new WebClient())
{
wc.Proxy = null;
wc.DownloadFile("http://www.farid.com/codes/code.html","code.html");
}
System.Diagnostics.Process.Start("code.html");
HTTP operations
WebRequest, WebResponse and WebClient classes have several
attributes and methods for HTTP operations like Cookie
management, QueryString management and etc.
You can more descriptions on these classes in the following book:
CSharp 3.0 in a Nutshell, 3rd Edition - O'Reilly
Write a HTTP server
We use HttpListener class for creating http server
static void Main( ) {
new System.Threading.Thread (Listen).Start( ); // Run server in parallel.
Thread.Sleep (500); // Wait half a second.
using (WebClient wc = new WebClient()) // Make a client request.
Console.WriteLine(wc.DownloadString("http://localhost:51111/MyApp/Request.txt"));
}
static void Listen() {
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:51111/MyApp/"); // Listen on
listener.Start(); // port 51111.
// Wait for a client request:
HttpListenerContext context = listener.GetContext(); // Respond to the request:
string msg = "You asked for: " + context.Request.RawUrl;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
context.Response.StatusCode = (int)HttpStatusCode.OK;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter(s))
writer.Write(msg);
listener.Stop();
}
OUTPUT: You asked for: /MyApp/Request.txt

This program create a synchronic http server.


FTP : File Transfer Protocol
This protocol is one of the application layer protocols that used for
file transfer operations.
using (WebClient wc = new WebClient()) {
wc.Proxy = null;
wc.Credentials = new NetworkCredential ("anonymous@albahari.com","");
wc.BaseAddress = "ftp://ftp.albahari.com/incoming/";
wc.UploadString("tempfile.txt", "hello!");
Console.WriteLine (wc.DownloadString ("tempfile.txt")); // hello!
}

WebClientclass used for connect via ftp protocol.


We can send different type of commands to ftp server like: listing files in a
directory or something like that.
Send email with SmtpClient
SmtpClient client = new SmtpClient();
client.Host = "mail.farid.net";
MailMessage mm = new MailMessage();
mm.Sender = new MailAddress ("kay@domain.com", "Kay");
mm.From = new MailAddress ("kay@domain.com", "Kay");
mm.To.Add (new MailAddress ("bob@domain.com", "Bob"));
mm.CC.Add (new MailAddress ("dan@domain.com", "Dan"));
mm.Subject = "Hello!";
mm.Body = “Hello World!”;
mm.IsBodyHtml = false;
client.Send(mm);
TCP
Classes in this section work in transport and network layers.
We can use these classes for TCP communications: TcpClient, TcpListener , Socket.

Client
using (TcpClient client = new TcpClient ("address", port))
using (NetworkStream n = client.GetStream())
{ // Read and write to the network stream... }

Server
TcpListener listener = new TcpListener (<ip address>, port);
listener.Start();
while (keepProcessingRequests)
using (TcpClient c = listener.AcceptTcpClient( ))
using (NetworkStream n = c.GetStream( ))
{ // Read and write to the network stream... }
listener.Stop ( );
Thank you

You might also like