C # Network Programming overview

Source: Internet
Author: User
Tags aliases bool function prototype int size connect socket port number visual studio
Programming | Network C # Network Programming overview

Microsoft's next-generation Internet development tool, Vs.net, was launched nationwide in March, and one of the emerging languages, C #, is being accepted and used by more and more developers.
C # As a collection of the long language of the family, in all aspects, especially the network programming has a great advantage. This article will introduce you to use C # for network programming some of the basic knowledge and methods.
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.

I would like to focus on some of the classes in C # Network programming: DNS class, Iphostentry class, IPEndPoint class and Socket class, finally I will give a corresponding example to deepen the reader's understanding.
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 = 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 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.

Finally, I will integrate the above C # network programming some knowledge, to show you a good example. This example is a synchronous-mode client application using a socket, which first establishes an endpoint by parsing the IP address of the server, and creates a socket connection based on a stream socket, which is used by the TCP protocol. Through the socket can be sent to get the page command, and then through the socket to get the default Web page, and finally through the file stream will be obtained data to the local file. This completes the webpage downloading work, the program operation effect 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
{

///
Summary description of the Form1.
///

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 ()
{
//
Required for Windows Forms Designer support
//

InitializeComponent ();

//
TODO: Add any constructor code after the InitializeComponent call
//

}


///
Clean up all resources that are in use.
///
protected override void Dispose (bool disposing)
{

if (disposing)

{
if (Components!= null)
{

Components. Dispose ();

}

}

Base. Dispose (disposing);

}


#region Windows Form Designer generated code

///

Designer supports required methods-do not use the Code editor to modify

The contents of 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 filename:";

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);


}

#endregion


///

The main entry point for the application.

///

[STAThread]

static void Main ()

{

Application.Run (New Form1 ());

}


private string Dosocketget (String server)

{

Define the 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 a list of server-related IP addresses, where the first item is what we need

IPAddress Hostadd = dns.resolve (server). ADDRESSLIST[0];


Creates an endpoint based on the IP address of the server being obtained, with the port default of 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, "Hint info",

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, Socketflags.none);

}

catch (Exception CE)

{

MessageBox.Show ("Send error:" +ce.) message, "Hint info",

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 page on 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)

{

Converts a read string to a byte array

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 to File

Fs. Write (content,0,content. Length);

}

catch (Exception Fe)

{

MessageBox.Show ("File creation/write error:" +fe.) message, "Hint information", messageboxbuttons.retrycancel,messageboxicon.information);

}

}

}

}


The above program is debugged through the Windows 2000 Server Edition, Visual Studio.NET Chinese official edition




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.