C # network programming

xiaoxiao2021-03-06  55

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 gets an ipaddress instance, which 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 get the corresponding iPhostRy instance through the gethostbyaddress () method, the gethostByname () method, function prototype as follows: public static IPHostEntry GetHostByAddress (string IPAddress); public static IPHostEntry GetHostByName (string hostName); the following code shows how IPHostEntry example use of the above two methods, respectively, contain information about the server www.google.com: IPHostEntry hostInfo = DNS.GethOSTBYADDRESS ("192.168.1.1"); iPhostentry Hostinfo = DNS.GETOSTBYNAME ("www.google.com"); When using the above method, you will have to handle the following exceptions: Socketexception is exception: Operation when accessing socket The system error trigger argumentnullexception: Parameter is an empty reference to trigger ObjectDisposedexception exception: Socket has been turned off, I briefly introduced some methods in the DNS class and its usage, and raise the abnormality that may appear, 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

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 use, you need to create Socket object instance, which may be achieved by the Socket class constructor: public Socket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType); wherein, AddressFamily Socket parameter specifies the addressing scheme used, such as AddressFamily.InterNetwork indicates 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, and the sockettype.dgram represents the connection 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 the Socket instance can be created, we can pass the endpoint of a remote host and it acquire the connection. The method used is the connection () method: public connect (EndPoint EP); this method can only be used on 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 and the process: 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 function prototype of the Send () method is as follows: Public int send (Byte [] Buffer, int size, 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 Some values: socketflags.none, 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 several functions that have been overloaded: public int send (byte [] buffer; public int send (byte [] buffer, socketflags flags; public int desund (byte [] buffer, INT Offset, int size, socketflags flags; introduced the send () method, the following is the Receive () method, its function prototype as follows: Public int received (byte [] buffer, int size, socketflags flags; parameters and Send () The parameters of the method are similar, and will not be described here. Similarly, the method has some of the following functions have been reached: public int received; 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 to disable the disabled type, SoketshutDown.send Indicates that the socket used to send; SoketShutdown.Receive indicates that the socket used to receive; and SoketShutdown.both indicates that the send and reception socket are simultaneously 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 called, the Close () method is called to close the socket, the prototype is as follows: public void close (); this method is forced to close a socket connection and release all managed resources and unmanaged resources. The method is actually called method Dispose (), 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, Also release managed resources and unmanaged resources; if false, only 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 work of the webpage. The effect of the program run is as follows: The source code is as follows: (where the main function is dosocketget ()) Using system; use system.drawing; use system.collections; using system.componentmodel; Using system.windows.forms; using system.d; using system.net; using system.text; using system.io; namespace socketsample {////// Form1 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 required designer variable. /// private system.componentmodel.container components = null; public form1 () {/// Windows Form Designer Support for // InitializationComponent (); /// Todo: Add any construct after INITIALIZECOMPONENT call Function code //} / / / / / Clean all the resources being used. /// protected {if (disponents! = null) {components.dispose ();}} Base.Dispose ();} #region Windows form designer generated code //// / /// Designer Support the required method - Do not use the code editor to modify the // / this method.

/// private void initializeComponent () {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.DO wnload.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);} #endregion // /// The primary entry point of the application.

/// [stathread] static void main () {Application.run (new form1 ());} private string dosocketget (String Server) {// Defines some necessary variables and a string eNCoding ASCII to send to the server = 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; // Gets the server-related IP address list, where the first item is for our IPAddress Hostadd = 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 {// connected to the server S.Connect (Ephost);} catch (exception se) {messagebox.show ("connection error:" se.Message, " Tips ", MessageBoxButthing.Retrycancel, MessageBoxicon.information;} if (! S.connected) {strretpage =" You cannot connect to the server! "; Return StrretPage;} Try {// Send a get command S.send to the server (byteget) , Byteget.Length, SocketFlags.none;} catch (Exception CE) {MessageBox.show ("Send Error:" Ce.Message, "Tips", MessageBoxButtissation;} // receive page data until all bytes are received int32 bytes = s.Receive (Recvbytes, Recvbytes.length, 0); strretpage = "The following is in server Default web page on " 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;

转载请注明原文地址:https://www.9cbs.com/read-87916.html

New Post(0)