17134 Networks

Embed Size (px)

Citation preview

  • 8/12/2019 17134 Networks

    1/35

    Networking in C#

  • 8/12/2019 17134 Networks

    2/35

    C# is a language designed for the modern computing

    environment, of which the Internet is, obviously, an important

    part.

    A main design criteria for C# was, therefore, to include those

    features necessary for accessing the Internet.

    Using standard features of C# and the .NET Framework, it is

    easy to Internet-enable your applications and write other

    types of Internet-based code.

  • 8/12/2019 17134 Networks

    3/35

    Primary namespace for networking isSystem.Net. It defines alarge number of highlevel, easy-to-use classes that support

    the various types of operations common to the Internet.

    Several namespaces nested under System.Net are alsoprovided. For example, low-levelnetworking control throughsockets is found inSystem.Net.Sockets.

    Mail support is found in System.Net.Mail. Support forsecure network streams is found inSystem.Net.Security.

    Another important networking-related namespace isSystem.Web. It supports ASP.NET-based networkapplications.

  • 8/12/2019 17134 Networks

    4/35

    System.Net

    Although System.Netdefines many members, only a few areneeded to accomplish mostcommon Internet programming tasks.

    At the core of networking are the abstract classes WebRequest

    andWebResponse.

    These classes are inherited by classes that support a specificnetwork protocol.

    For example, the derived classes that support the standard HTTP

    protocol areHttpWebRequestandHttpWebResponse.

    Even thoughWebRequestandWebResponseare easy to use, forsome tasks, you canemploy an even simpler approach based on

    WebClient.

    For example, if you only need toupload or download a file, then

    WebClientis often the best way to accomplish it.

  • 8/12/2019 17134 Networks

    5/35

    Uniform Resource Identifiers

    Fundamental to Internet programming is the Uniform Resource

    Identifier(URI).

    A URI describes the location of some resource on the network. A

    URI has the following simplified general form:

    Protocol://HostName/FilePath?Query

    Protocolspecifies the protocol being used, such as HTTP.

    HostName identifies a specific server, such as or

    www.HerbSchildt.com. FilePathspecifies the path to a specific file.

    Queryspecifies information that will be sent to the server. Query

    is optional.

    In C#, URIs are encapsulated by theUri class.

  • 8/12/2019 17134 Networks

    6/35

    Since WebRequest and WebResponse are main classes of

    System.Net, they are discussed as:

  • 8/12/2019 17134 Networks

    7/35

    WebRequest

    TheWebRequest class manages a network request. It is abstract

    because it does not implement a specific protocol. It does, however,

    define those methods and properties common to all requests.

    WebRequestdefines no public constructors.

    To send a request to a URI, you must first create an object of a class

    derived fromWebRequestthat implements the desired protocol.

    This can be done by callingCreate( ), which is a static methoddefined byWebRequest. Create( ) returns an object of a class that

    inheritsWebRequestand implements a specific protocol.

  • 8/12/2019 17134 Networks

    8/35

    Methods of WebRequest class

  • 8/12/2019 17134 Networks

    9/35

  • 8/12/2019 17134 Networks

    10/35

    WebResponse

    WebResponseencapsulates a response that is obtained as theresult of a request.

    WebResponse is an abstract class. Inheriting classes create

    specific, concrete versions of it that support a protocol.

    AWebResponseobject is normally obtained by calling theGetResponse( )methoddefined byWebRequest.

    This object will be an instance of a concrete class derivedfromWebResponsethat implements a specific protocol.

  • 8/12/2019 17134 Networks

    11/35

    Methods of WebResponse class

  • 8/12/2019 17134 Networks

    12/35

    HttpWebRequest and HttpWebResponse

    The classes HttpWebRequest and HttpWebResponse

    inherit the WebRequest and WebResponse classes and

    implement theHTTP protocol.

  • 8/12/2019 17134 Networks

    13/35

    using System;

    using System.Net;

    using System.IO;

    class NetDemo {

    static void Main() {

    int ch;

    // First, create a WebRequest to a URI.HttpWebRequest req = (HttpWebRequest)

    WebRequest.Create("http://www.McGraw-Hill.com");

    // Next, send that request and return the response.

    HttpWebResponse resp = (HttpWebResponse)

    req.GetResponse();

    // From the response, obtain an input stream.

    Stream istrm = resp.GetResponseStream();

  • 8/12/2019 17134 Networks

    14/35

    /*Now, read and display the html present at the specified URI. So you

    can see what is being displayed, the data is shown 400 characters at a

    time. After each 400 characters are displayed, you must press ENTERto get the next 400. */

    for(int i=1; ; i++) {

    ch = istrm.ReadByte();

    if(ch == -1) break;Console.Write((char) ch);

    if((i%400)==0) {

    Console.Write("\nPress Enter.");

    Console.ReadLine();

    }}

    resp.Close();

    }}

  • 8/12/2019 17134 Networks

    15/35

    The Uri Class

    WebRequest.Create( ) has two different versions.

    1. One accepts the URI as a string. This is the version used by

    the preceding programs.

    2. The other takes the URI as an instance of the Uri class,which is defined in the System namespace.

    The Uri class

    encapsulates a URI. Using Uri, you can construct a URI thatcan be passed to Create()

  • 8/12/2019 17134 Networks

    16/35

    class UriDemo {static void Main() {

    Uri sample = new Uri("http://HerbSchildt.com/somefile.txt ");

    Console.WriteLine("Host: " + sample.Host);

    Console.WriteLine("Port: " + sample.Port);

    Console.WriteLine("Scheme: " + sample.Scheme);

    }

    }

  • 8/12/2019 17134 Networks

    17/35

    The output is shown here:

    Host: HerbSchildt.com

    Port: 80

    Scheme: httpLocal Path: /somefile.txt

    Query: ?SomeQuery

    Path and query: /somefile.txt?SomeQuery

  • 8/12/2019 17134 Networks

    18/35

    Using WebClient

    If your application only needs to upload or download data to

    or from the Internet, then you can use WebClient.

    Example

  • 8/12/2019 17134 Networks

    19/35

    IPAddress Class

    AnIPAddressobject is used to represent a single IP address.

    This value can then be used in the various socket methods to

    represent the IP address.

    The default constructor for IPAddress is as follows:public IPAddress(longaddress)

    Some of the methods associated with IPAddress class are as

    follows:

  • 8/12/2019 17134 Networks

    20/35

  • 8/12/2019 17134 Networks

    21/35

    The Parse() method is most often used to create IPAddress

    instances:

    IPAddressnewaddress = IPAddress.Parse("192.168.1.1");

    This format allows you to use a standard dotted quad IPaddress in string format and convert it to an IPAddress object.

  • 8/12/2019 17134 Networks

    22/35

    The IPAddress class also provides four read-only fields that

    represent special IP addresses for use in programs:

    Any

    Used to represent any IP address available on the local

    system

    Broadcast

    Used to represent the IP broadcast address for the local

    network

    Loopback

    Used to represent the loopback address of the system

    None

    Used to represent no network interface on the system

  • 8/12/2019 17134 Networks

    23/35

    IPHostEntry hostDnsEntry = Dns.GetHostEntry("localhost");

    foreach(IPAddress address in hostDnsEntry.AddressList)

    {

    Console.WriteLine("Type: {0}, Address: {1}",

    address.AddressFamily, address);}

    //example console application 17

  • 8/12/2019 17134 Networks

    24/35

    the method used to obtain the local IP address:

    IPHostEntry i =

    Dns.GetHostByName(Dns.GetHostName());

    IPAddress myself = i.AddressList[0];

  • 8/12/2019 17134 Networks

    25/35

    using System;

    using System.Net;

    class AddressSample{

    public static void Main ()

    {

    IPAddress test1 = IPAddress.Parse("192.168.1.1");IPAddress test2 = IPAddress.Loopback;

    IPAddress test3 = IPAddress.Broadcast;

    IPAddress test4 = IPAddress.Any;

    IPAddress test5 = IPAddress.None;

  • 8/12/2019 17134 Networks

    26/35

    IPHostEntry ihe =

    Dns.GetHostByName(Dns.GetHostName());

    IPAddress myself = ihe.AddressList[0];if (IPAddress.IsLoopback(test2))

    Console.WriteLine("The Loopback address is: {0}",

    test2.ToString());

    else

    Console.WriteLine("Error obtaining the loopback address");

    Console.WriteLine("The Local IP address is: {0}\n",

    myself.ToString());}

    }

    } /// window application 18

  • 8/12/2019 17134 Networks

    27/35

    Socket

    A socketis one endpoint of a two-way communication link

    between two programs running on the network. A socket is

    bound to a port number so that the TCP layer can identify the

    application that data is destined to be sent.

    An endpoint is a combination of an IP address and a port

    number. Every TCP connection can be uniquely identified by

    its two endpoints. That way you can have multiple connections

    between your host and the server.

  • 8/12/2019 17134 Networks

    28/35

    Sockets are the fundamental technology for programming

    software to communicate on TCP/IP networks. A socket

    provides a bidirectional communication endpoint for sending

    and receiving data with another socket. Socket connections

    normally run between two different computers on a LAN oracross the Internet, but they can also be used for inter-process

    communication on a single computer.

  • 8/12/2019 17134 Networks

    29/35

    The socket defines the following:

    A specific communication domain, such as a network

    connection

    A specific communication type, such as stream or datagram

    A specific protocol, such as TCP or UDP

    After the socket is created, it must be bound to either a specific

    network address and port on the system, or to a remote network

    address and port. Once the socket is bound, it can be used to

    send and receive data from the network.

  • 8/12/2019 17134 Networks

    30/35

    The following example creates a Socket that can be used to

    communicate on a TCP/IP-based network, such as the Internet.

    Socket s = new Socket(AddressF amily.I nterN etwork,

    SocketType.Str eam, Pr otocolType.Tcp);

    the AddressFamily.InterNetwork member specifies the IP

    version 4 address family).

    ProtocolType.Tcp indicates that the socket uses

    TCP;ProtocolType.Udpindicates that the socket uses UDP).

    SocketType.Stream member indicates a standard socket forsending and receiving data with flow control).

  • 8/12/2019 17134 Networks

    31/35

    in .NET, there is a class underSystem.Netnamespace

    called IPEndPoint, which represents a networkcomputer as an IP address and a port number.

    public IPEndPoint(System.Net.IPAddress address,int port);

    you can send data to the other side using

    theSendmethod of theSocket class.

  • 8/12/2019 17134 Networks

    32/35

    Try

    {

    String s= "I am here";

    byte[] byData = System.Text.Encoding.ASCII.GetBytes(s);

    m_socClient.Send(byData);

    }

    catch (SocketException se)

    {

    MessageBox.Show ( se.Message );

    }

  • 8/12/2019 17134 Networks

    33/35

    Similar to Send, there is a Receive method on

    the Socket class. You can receive data using the

    following call:

    byte [] buffer = new byte[1024];int i = m_socClient.Receive (buffer);

  • 8/12/2019 17134 Networks

    34/35

    Listen causes a connection-oriented Socket to listen for

    incoming connection attempts. Thebacklogparameter specifies

    the number of incoming connections that can be queued for

    acceptance. To determine the maximum number ofconnections you can specify, retrieve theMaxConnections

    value.

    Socket listenSocket = new

    Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

    IPEndPoint ep = new IPEndPoint(hostIP, port);

    listenSocket.Bind(ep);

    listenSocket.Listen(backlog);

    http://msdn.microsoft.com/en-us/library/system.net.sockets.socketoptionname.aspxhttp://msdn.microsoft.com/en-us/library/system.net.sockets.socketoptionname.aspx
  • 8/12/2019 17134 Networks

    35/35