C # Network Programming Overview Microsoft Next-Generation Internet Development Tools VS.NET has been launched nationwide in March, one of the emerging language C # is being accepted and applied by more and more developers. C # As a long language of a collection, there is a great advantage in all aspects, especially network programming. This article introduces you some basic knowledge and methods for network programming with C #. Microsoft's .NET Framework provides us with two namespaces for us: System.net and System.Net.Sockets. By reasonable use of the classes and methods, we can easily write a variety of web applications. This network application can either generate a stream sleeve, or may be based on a data sheet. And the most widely used protocol based on the communication-based communication is the TCP protocol, and the most widely natural use of the data report-based communications is the UDP protocol.
Below I will introduce some classes in C # network programming: DNS class, iPhostentry class, IpendPoint, and socket classes, and finally I will give the corresponding instance to deepen the reader's understanding. DNS class:
Provide domain name services to applications that use TCP / IP Internet services. Its Resolve () method queries the DNS server to map the user-friendly domain name (such as "www.google.com") to the Internet address (e.g., 192.168.1.1). The resolve () method returns an iPhostenty instance that contains the address of the requested name and alias. In most cases, you can use the first address returned in the AddressList array.
The result of the resolve () method is as follows:
Public Static iphostentry resolve (string hostname);
The following code acquires an 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 get the corresponding iPhostRy instance through the gethostbyaddress () method, and gethostbyname () method, 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 the above two ways to get the iPhostentry instance of information about the server www.google.com:
IPHOSTENTRY HOSTINFO = DNS.GETHOSTBYADDRESS ("192.168.1.1");
IPHOSTENTRY HOSTINFO = DNS.GETHOSTBYNAME ("www.google.com");
When using the above method, you may have to handle the following exceptions:
Socketexception is exception: Errors occur when the operating system occurs when accessing socket
Argumentnullexception is abnormal: parameters are empty references
ObjectdisposedException: Socket has been turned off
With the above, I briefly introduced some methods in the DNS class and their usage, and raise the possible exceptions, let us go to the iPhostentry class that is closely related to the DNS class. IPHOSTENTRY Class: The instance object of this class contains address information about the Internet host. All public static members of this type are secure for multi-threaded operations, but not to ensure that any instance members are threads. Some of these properties are: addressList properties, aliases properties, and hostname properties.
The use of AddressList properties and aliases properties is the list of IP addresses associated with the host, respectively, and gain or set the alias list associated with the host. Where the addressList property is an array of ipaddress types, which contains the IP address of the host name contained in the AliaSES property; the AliaSs property value is a set of strings, which contains the DNS name of the IP address resolved into the AddressList property. The HostName property is better understood that it contains the main host name of the server. This light can know from the name. If the server's DNS item defines an additional alias, you can use these alias in the AliaSes property.
The following code lists the relevant alias lists of the server www.google.com and the length of the IP address list 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 { Console.writeLine (Addr [i]); } Introduce the iPhostentry class, we can get the relevant IP addresses and alias lists of the host to which you want to connect, but you really want to get a connection with the host. IpendPoint class: In Internet, TCP / IP uses a network address and a service port number to uniquely identify the device. Network Address Identify Specific Device on the Network; port number identifies specific services to which the device to be connected. The combination of network addresses and service ports is called endpoints, which is the endpoint class in the .NET framework, which provides information indicating the abstraction of network resources or services, to log network addresses. .NET also defines the sub-generation of EndPoint for each supported address family; for IP address family, this class is IpendPoint. The IpendPoint class contains the host and port information required for the application to connect to the service on the host, and the Host IP address and port number, the IpendPoint class form to the service connection point. There are two very useful constructor in the IpendPoint class: Public IpendPoint (long, int); Public IpendPoint (ipaddress, int); Their role is to initialize new instances of the IpendPoint class with the specified address and port number. The properties in this class are: address properties, addressFamily properties, and port properties, these properties are relatively easy to understand, this is not described more. The following code shows how to get the endpoint of the 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 some of the necessary basic classes that have been connected to the host. With these knowledge, we can use the Socket class to actually connect and communicate with the host. Socket class: The Socket class is a very important class that is included in the System.Net.Sockets name space. A Socket instance contains a local and remote endpoints, just as described above, the endpoint contains some relevant information of the Socket instance. It is necessary to know that the Socket class supports two basic modes: synchronous and asynchronous. The difference is that in the synchronous mode, the call to the function of the network operation (such as Send and Receive) will continue to return the control to the call after the operation is completed. In asynchronous mode, these calls return immediately. Let's focus on the Socket programming of the synchronous mode. First, the basic process of Socket programming of the synchronous mode is as follows: 1. Create a Socket instance object. 2. Connect the above instance object to a specific endpoint (endpoint). 3. After the connection is completed, you can communicate with the server: receive and send information. 4. Communication is completed, use the shutdown () method to disable the socket. 5. Finally, use a Close () method to close the socket. I know the above basic procedure, we have begun to further achieve and communicate. Before you use, you need to first create an instance of the socket object, which can be implemented by the construction method of the Socket class: Public Socket (AddressFamily AddressFamily, SocketType Sockettype, ProtocolType Protocoltype); Where the AddressFamily parameter specifies the addressing scheme for the socket, such as the address of the IP version 4; the sockettype parameter specifies the type of socket, such as SocketType.Stream indicates that the connection is based on a streamlined, while sockettype.dgram means The connection is based on the data setup. The protocoltype parameter specifies the protocol used by the socket, such as ProtocolType.TCP indicates that the connection protocol is used by TCP protocol, and protocol.udp indicates that the connection protocol is used to use UDP protocol. After creating a socket instance, we can use the endpoint of a remote host and the method to connect, the method used is the connect () method: Public Connect (EndPoint EP); This method can only be applied to the client. After the connection, we can use the connect of the connectivity to verify that the connection is successful. If the returned value is True, the connection is successful, otherwise it is failed. The following code shows how to create a socket instance and get a connection through the 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 = New Socket (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 request () methods to communicate. The SEND () method is the function prototype as follows: Public int send (Byte [] Buffer, int size, socketflags flags; Where the parameter buffer contains the data to be sent, the parameter size indicates the size of the data to send, and the parameter FLAGS can be some of the following values: socketflags.dontroute, socketflags.outofbnd. This method returns a value of a System.Int32 type that indicates the size of the transmitted data. At the same time, the method has the following functions that have been overloaded: Public int send (Byte [] buffer; Public int send (Byte [] Buffer, SocketFlags Flags; Public int send (Byte [] Buffer, int offset, int size, socketflags flags; Introduce the Send () method, the following is the received () method, its function prototype is as follows: Public int received (Byte [] Buffer, int size, socketflags flags; The parameters of these parameters are similar to the parameters of the Send () method, and will not be described here. Similarly, this method has some of the following functions that have been overloaded: Public int 10; Public int received (Byte [] Buffer, SocketFlags Flags; Public int received (Byte [] Buffer, int offset, int size, socketflags flags; After the communication is complete, we disable the Socket through the shutdown () method, the function prototype is as follows: Public void Shutdown (socketshutdown how); The parameter HOW indicates the type of disabled, indicates that the socketshutdown.send is turned off; SoketShutdown.Receive indicates that the sockets used to receive; and SoketShutdown.both indicates that the send and receive socket simultaneously is closed. It should be noted that the shutdown () method must be invoked before calling the Close () method to ensure that all pending data is sent or received before the Socket is turned off. Once the shutdown () is completed, the close () method is called to close the socket, and its function prototype is as follows: Public void close (); This method forces a socket connection and release all managed resources and unmanaged resources. The method is actually called method Dispose () internally, which is protected, and its function prototype is as follows: Protected Virtual Void Dispose (Bool Disposing); where the parameter disposing is true or false, if True, the managed resource and the non-hosting resource are simultaneously released; if false, only the non-hosting resources are released. Because the parameters when the close () method calls the dispose () method is True, it releases all managed resources and unmanaged resources. In this way, a Socket is completed from the process of creating to the final closure of the communication. Although the entire process is more complicated, Socket programming is performed relative to the SDK or other environments, this process is quite relaxed. Finally, I will show a good example to you with some knowledge of the C # network programming. This example is a client application that uses Socket based synchronous mode, which first establishes an endpoint by parsing the IP address of the server, and creates a streamlined socket connection, the protocol used is the TCP protocol. With this Socket, you can send a command to obtain a web page, and then obtain the default web page on the server through the Socket, and finally the data obtained by the file stream will be written to the local file. This completes the download of the web page, and the effect of the program is as follows: The source code is as follows: (The main function is dosocketget ()) using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets; using System.Text; using System. IO; Namespace socketsample { // /// /// Form1's summary description. /// Public class form1: system.windows.forms.form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button Download; private System.Windows.Forms.TextBox ServerAddress; private System.Windows.Forms.TextBox Filename; // / / The designer variable must be designed. /// Private system.componentmodel.Container Components = NULL; Public Form1 () {/// Windows Form Designer Support for // InitializationComponent (); /// tDO: Add any constructor code after INITIALIZECOMPONENT calls // } / / / / / Clean all the resources being used. /// Protected Override Void Dispose (Bool Disposing) { IF (Disposing) {IF (Components! = NULL) { Components.dispose (); } } Base.dispose (Disposing); } #Region Windows Form Designer Generated Code /// /// Designer supports the required method - do not use the code editor to modify /// This method is content. /// Private vidinitiRizeComponent () { THIS.LABEL1 = New System.windows.Forms.label (); THIS.LABEL2 = New System.windows.Forms.label (); This.Download = new system.windows.Forms.Button (); This.Serveraddress = new system.windows.Forms.TextBox (); This.FileName = new system.windows.Forms.TextBox (); THIS.SUSPENDLAYOUT (); // // label1 // THIS.Label1.Location = new system.drawing.point (16, 24); THIS.LABEL1.NAME = "label1"; THIS.Label1.size = new system.drawing.size (80, 23); this.label1.tabindex = 0; This.Label1.Text = "server address:"; THIS.Label1.TextAlign = system.drawing.contentAlignment.middleright; // // label2 // THIS.LABEL2.LOCATION = New System.drawing.Point (16, 64); THIS.LABEL2.NAME = "label2"; THIS.Label2.size = new system.drawing.size (80, 23); THIS.Label2.tabindex = 1; This.Label2.Text = "Local file name:"; THIS.Label2.TextAlign = system.drawing.contentAlignment.middleright; // // Download // This.Download.location = new system.drawing.point (288, 24); this.Download.name = "Download"; this.download.tabindex = 2; this.Download.text = "Start download"; This.Download.click = new system.eventhandler (this.Download_click); // // serveraddress // This.Serveraddress.Location = new system.drawing.point (96, 24); This.Serveraddress.name = "serveraddress"; This.Serveraddress.size = new system.drawing.size (176, 21); THIS.SERVERADDRESS.TABINDEX = 3; THIS.SERVERADDRESS.TEXT = ""; // // filename // This.filename.location = new system.drawing.point (96, 64); This.FileName.Name = "filename"; This.filename.size = new system.drawing.size (176, 21); this.filename.tabindex = 4; THIS.FILENAME.TEXT = "" // // Form1 // THIS.AUTOSCALEBASESIZE = New System.drawing.size (6, 14); THIS.CLIENTSIZE = New System.drawing.size (376, 117); this.controls.addrange (new system.windows.forms.control] { THIS.FILENAME, this.Serveraddress, this.Download, THIS.LABEL2, THIS.LABEL1}); THIS.NAME = "Form1"; THIS.TEXT = "Web downloader"; This.ResumeLayout (false); } #ndregion /// /// The main entry point for the application. /// [Stathread] Static void main () { Application.run (New Form1 ()); } Private string dosocketget (String Server) { / / Define some necessary variables and a string to send to the server ENCODING ASCII = Encoding.ASCII; String get = "Get / http / 1.1 / r / nhost:" Server "/ r / nConnection: Close / R / N / R / N"; Byte [] Byteget = ascii.getbytes (GET); Byte [] recvbytes = new byte [256]; String strretpage = null; / / Get the list of IP addresses related to the server, where the first item is what we need. Ipaddress hostd = dns.resolve (server) .addresslist [0]; / / Create a endpoint based on the IP address of the obtained server, the port is the default 80 IpendPoint Ephost = New IpendPoint (HostAdd, 80); // Create a Socket instance Socket S = New Socket (AddressFamily.InterNetwork, Sockettype.Stream, Protocoltype.tcp); Try { // Connect to the server with the endpoint obtained above S.Connect (Ephost); } Catch (Exception SE) { Messagebox.show ("Connection error:" se.Message, "Tips", MessageboxButtons.Retrycancel, MessageBoxicon.information; } IF (! S.Connected) { StrretPage = "Cannot connect to the server!"; Return StrretPage; } Try { / / Send a get command to the server s.send (byteget, byteget.length); } Catch (Exception CE) { Messagebox.show ("Send Error:" Ce.Message, "Tips Information", MessageboxButtons.Retrycancel, MessageBoxicon.information; / / Receive page data until all bytes are received INT32 bytes = S.Receive (Recvbytes, Recvbytes.length, 0); StrretPage = "The following is the default web page on the server" Server "; / r / n"; StrretPage = strretpage ascii.getstring (recvbytes, 0, bytes); While (bytes> 0) { Bytes = S.Receive (Recvbytes, Recvbytes.length; SocketFlags.none); StrretPage = strretpage ascii.getstring (recvbytes, 0, bytes); } // Disable and close the Socket instance S.SHUTDOWN (SocketShutdown.both); s.close (); Return StrretPage; } Private void Download_Click (Object Sender, System.EventArgs E) { // convert the read string to byte arrays Byte [] content = encoding.ascii.getbytes (dosocketget (serveraddress.text)); Try { // Create a file stream object instance FILESTREAM FS = New FileStream (FileName.Text, FileMode.Openorcreate, FileAccess.Readwrite); // Write file fs.write (Content, 0, Content.length); } Catch (Exception Fe) { Messagebox.show ("File Create / Write Error:" Fe.Message, MessageBoxButtons.Retrycancel, MessageBoxicon.information; } } } } The above program is in the Windows 2000 server version, Visual Studio.net Chinese official version of the debugging