Network Programming in C#
Network Programming in C#
Network Programming in C#
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]");
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
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