Structure. NET environment of Web page Downloader (1)

Source: Internet
Author: User
Tags aliases function prototype int size socket dns names port number
Web page | Download one. Objective:

Microsoft's. NET Framework provides the following two namespaces for our network programming: System.Net and System.Net.Sockets. By using the classes and methods reasonably, we can easily write a variety of Web applications. This type of network application can be based either on a stream socket or on a datagram socket. The most widely used protocol based on stream sockets is the TCP protocol, and the most widely used communication based on datagram sockets is the UDP protocol. Next I will focus on the introduction to you. NET network programming in some classes: DNS class, Iphostentry class, IPEndPoint class and Socket class, and will give a Web page downloader at the end of the example to deepen the reader. NET network programming understanding.

Two Network Programming class Introduction:

Dns class:

Provides domain name services to applications that use TCP/IP Internet services. Its resolve () method queries the DNS server to map user-friendly domain names (such as "www.google.com") to digital forms of Internet addresses (such as 192.168.1.1). The Resolve () method returns a Iphostenty instance that contains a list of addresses and aliases for the requested name. In most cases, you can use the first address returned in the AddressList array.

The function prototype for the Resolve () method is as follows:

public static Iphostentry Resolve (string hostName);



The following code gets a IPAddress instance that contains the IP address of the server www.google.com:

Iphostentry iphostinfo = dns.resolve ("www.google.com");
IPAddress ipaddress = iphostinfo.addresslist[0];



However, in the DNS class, in addition to the resolve () method, you can also use the Gethostbyaddress () method and the GetHostByName () method to get the corresponding Iphostentry instance, the function prototype is as follows:

public static Iphostentry gethostbyaddress (string ipaddress);
public static Iphostentry gethostbyname (string hostName);



The following code shows how to use each of these methods to obtain a Iphostentry instance that contains information about the server www.google.com:

Iphostentry hostinfo=dns.gethostbyaddress ("192.168.1.1");
Iphostentry hostinfo=dns.gethostbyname ("www.google.com");



When you use the above method, you will probably need to deal with the following kinds of exceptions:

SocketException Exception: An operating system error occurred while accessing the socket

ArgumentNullException exception: The parameter is thrown by a null reference

ObjectDisposedException exception: The socket has been closed to raise

Above, I give you a brief introduction to some of the methods in the DNS class and their usage, and enumerate the possible exceptions, let's go to the Iphostentry class, which is closely related to the DNS class.

Iphostentry class:

The instance object of this class contains information about the address of the Internet host. All public static members of this type are safe for multithreaded operations, but do not guarantee that any instance members are thread safe. Some of the main properties are: AddressList property, aliases property, and hostname property.

The function of the AddressList property and the aliases property is to get or set the list of IP addresses associated with the host and to get or set the list of aliases associated with the host. Where the AddressList property value is an array of IPAddress types containing the IP address that resolves to the host name contained in the aliases property; The Aliases property value is a set of strings containing the DNS names resolved to the IP addresses in the AddressList attribute. The Hostname property is better understood, it contains the main hostname of the server, the light from the name can be known. You can use these aliases in the Aliases property if the DNS entries for the server define additional aliases.

The following code lists the list of related names for server www.google.com and the length of IP address lists and lists all IP addresses:

Iphostentry iphost = dns.resolve ("www.google.com/");
string[] aliases = iphost.aliases;
Console.WriteLine (aliases. Length);

ipaddress[] addr = iphost.addresslist;
Console.WriteLine (addr. Length);
for (int i= 0; i < addr. Length; i++)
{
Console.WriteLine (Addr[i]);
}



After introducing the Iphostentry class, we can get the relevant IP address and alias list of the host we want to connect with, but it also needs a very important class-ipendpoint class to get the connection with the host.



IPEndPoint class:

In the Internet, TCP/IP uses a network address and a service port number to uniquely identify the device. The network address identifies a specific device on the network, and the port number identifies the specific service on the device to which you want to connect. The combination of a network address and a service port is called an endpoint, and it is the endpoint class that represents the endpoint in the. NET Framework, providing an abstraction that represents a network resource or service, to mark information such as a network address. NET also defines the descendants of endpoint for each supported address family, and for the IP address family, the class is IPEndPoint. The IPEndPoint class contains the host and port information required by the application to connect to the service on the host, and the IPEndPoint class forms to the service's connection point by combining the host IP address and port number of the service.

There are two very useful constructors in the IPEndPoint class:

Public IPEndPoint (long, int);
Public IPEndPoint (ipaddress, int);



Their role is to initialize a new instance of the IPEndPoint class with the specified address and port number. The properties in this class include the Address property, the AddressFamily property, and the Port property, which is relatively easy to understand and is not covered here. The following code shows how to get the endpoint of a server www.google.com:

Iphostentry iphost = dns.resolve ("www.google.com");
ipaddress[] addr = iphost.addresslist;
IPEndPoint EP = new IPEndPoint (addr[0],80);



In this way, we have learned the necessary basic classes to connect with the host, and with this knowledge, we can use the following socket class to really connect with the host and communicate.

Socket class:

The socket class is a very important class that is contained in the System.Net.Sockets namespace. A socket instance contains a local and a remote endpoint, as described above, which contains some relevant information about the socket instance.

What you need to know is that the socket class supports two basic modes: synchronous and asynchronous. The difference is that in synchronous mode, calls to functions that perform network operations, such as send and receive, wait until the operation completes before returning control to the calling program. In asynchronous mode, these calls are returned immediately.

Here we focus on the synchronous mode of socket programming. First, the basic process of synchronous mode socket programming is as follows:

1. Creates a socket instance object.

2. Connect the above instance object to a specific endpoint (EndPoint).

3. When the connection is complete, you can communicate with the server: Receive and send the message.

4. After the communication is complete, use the shutdown () method to disable the socket.

5. The close () method is used to turn off the socket.

Knowing the above basic process, we began to further implement the connection and communication. Before using, you need to create an instance of the socket object first, which can be done by constructing the socket class:

Public Socket (AddressFamily addressfamily,sockettype
Sockettype,protocoltype protocoltype);



Where the AddressFamily parameter specifies the addressing scheme used by the socket. For example, AddressFamily.InterNetwork indicates the address of IP version 4; sockettype parameter specifies the type of socket, for example, SocketType.Stream indicates that the connection is based on a stream socket, and Sockettype.dgram indicates that the connection is based on a number It was reported that the sockets were received. The ProtocolType parameter specifies the protocol used by the socket, for example, PROTOCOLTYPE.TCP indicates that the connection protocol uses the TCP protocol, while the PROTOCOL.UDP indicates that the connection protocol uses the UDP protocol.

After creating the socket instance, we can get a connection through the endpoint of a remote host, using the Connect () method:

Public Connect (EndPoint EP);



The method can only be applied to the client. Once connected, we can use the connected property of the socket to verify the success of the connection. If the value returned is true, the connection succeeds or fails. The following code shows how to create a socket instance and get a connection through an endpoint:

Iphostentry iphost = dns.resolve ("http://www.google.com/");
string []aliases = iphost.aliases;
ipaddress[] addr = iphost.addresslist;
EndPoint EP = new IPEndPoint (addr[0],80);

Socket sock = Newsocket (AddressFamily.InterNetwork,
SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);
Sock. Connect (EP);
if (sock. Connected)
Console.WriteLine ("OK");



Once the connection is successful, we can use the Send () and receive () methods to communicate.

The function prototype for the Send () method is as follows:

public int Send (byte[] buffer, int size, socketflags flags);



Where the parameter buffer contains the data to send, the parameter size indicates the size of the data to be sent, and the parameter flags can be some of the following values: Socketflags.none, Socketflags.dontroute, Socketflags.outofbnd.

The method returns a value of the System.Int32 type, which indicates the size of the sent data. At the same time, the method also has several overloaded function implementations:

public int Send (byte[] buffer);
public int Send (byte[] buffer, socketflags flags);
public int Send (byte[] buffer,int offset, int size,
SocketFlags flags);



The Send () method is described, followed by the receive () method, which has the following function prototype:

public int Receive (byte[] buffer, int size, socketflags flags);



The arguments are similar to the parameters of the Send () method, and are not included here.

Similarly, the method has some of the following function implementations that have been overloaded:

public int Receive (byte[] buffer);
public int Receive (byte[] buffer, socketflags flags);
public int Receive (byte[] buffer,int offset, int size,
SocketFlags flags);



After the communication is complete, we disable the socket via the shutdown () method, which is the following function prototype:

public void ShutDown (SocketShutdown);



The parameters of the How to indicate the type of disabled, Soketshutdown.send indicates that the socket used for forwarding is turned off, soketshutdown.receive indicates that the socket used for the receive is turned off, and Soketshutdown.both indicates that the socket being sent and received is closed at the same time.

It should be noted that the shutdown () method must be called before the Close () method is called to ensure that all pending data is sent or received before the socket closes. Once the shutdown () call completes, the close () method is invoked to turn off the socket, which has the following function prototype:

public void close ();



This method forces a socket connection to close and frees all managed and unmanaged resources. The method internally actually calls the method Dispose (), which is a protected type, and its function prototype is as follows:

protected virtual void Dispose (bool disposing);



Where the parameter disposing is true or false, and if true, both managed and unmanaged resources are released, and if False, only unmanaged resources are freed. Because the close () method calls the Dispose () method when the argument is true, it frees all managed and unmanaged resources.

In this way, a socket from the creation to the connection to the final closure of the communication process is completed. Although the whole process is more complex, but compared to the previous SDK or other environment for socket programming, the process is quite easy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.