Visual c#.net Network Program Development-socket Chapter 1th/2 page _c# Tutorial

Source: Internet
Author: User
Tags bind
Visual c#.net Network program Development-socket article
Author: Correspondent

Author: www.ASPCool.com

The Microsoft.NET Framework provides tiered, scalable, and regulated network services for applications to access the Internet. Its namespace system.net and System.Net.Sockets contain rich classes to develop a variety of Web applications. NET class allows applications to access the network at different levels of control, and developers can choose for different levels of programming as needed, almost all of the internet's needs-from socket sockets to normal requests/responses, and more importantly, This layering can be scaled to accommodate the ever-expanding needs of the Internet.

Put aside the 7-tier architecture of the Iso/osi model, from the logical level on the TCP/IP model. NET classes can be considered to contain 3 levels: The request/Response layer, the Application protocol layer, and the transport layer. Webreqeust and WebResponse represent the request/response layer, classes that support HTTP, TCP, and UDP compose the application protocol layer, while the socket class is at the transport layer. Can be indicated as follows:


Visible, the transport layer is at the bottom of the structure, and when the application protocol layer and the request/response layer above it cannot meet the special needs of the application, it is necessary to use this layer for socket socket programming.

And in. Net, the System.Net.Sockets namespace provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to tightly control network access. All other network access classes in the System.Net namespace are based on this socket socket implementation, such as the TcpClient, TcpListener, and UdpClient classes encapsulate details about the TCP and UDP connections that are created to the Internet The NetworkStream class provides the underlying data stream for network access, and many common Internet services can see the socket, such as Telnet, Http, Email, Echo, and so on, which, although the definition of communication protocol protocol is different , but the underlying transmission is the socket used.

In fact, a socket can be considered a data channel like a stream stream, which is built between the application side (client) and the remote server, and then the read (receive) and write (send) of the data are directed at this channel.


Visible, after the socket object is created on the application or server side, you can use the Send/sentto method to send data to the connected socket or use the Receive/receivefrom method to receive data from the connection socket;

For socket programming, the. NET Framework socket class is the managed code version of the socket service provided by the Winsock32 API. There are a number of ways to implement network programming, and in most cases the Socket class method simply marshals the data to their native Win32 copy and handles any necessary security checks. If you are familiar with the Winsock API functions, then use the socket class to write a Web program is very easy, of course, if you have not been contacted, it will not be too difficult, follow the explanations below, you will find that the use of the socket class to develop Windows network applications are originally subject to search, They follow roughly the same steps in most cases.

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, the SocketType parameter specifies the type of the socket, and the ProtocolType parameter specifies the protocol used by the socket.

The following example statement creates a Socket that can be used to communicate on a TCP/ip-based network, such as the Internet.

Socket s = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);


To use UDP instead of TCP, you need to change the protocol type, as shown in the following example:

Socket s = new socket (addressfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);


Once you create the Socket, on the client side, you will be able to connect to the specified server via the Connect method and send data to the remote server via the Send/sendto method, which can then receive data from the server via Receive/receivefrom; You need to bind the specified interface with the Bind method to make the socket connected to a local endpoint and listen for requests on that interface through the Listen method, calling accept to complete the connection, and creating a new socket to handle incoming connection requests, when the connection is heard from the client. When you are finished using the socket, remember to disable the socket using the Shutdown method and close the socket using the closing method. The methods/functions used are:

Socket.connect method: Establish a connection to a remote device
public void Connect (EndPoint remoteep) (with overloaded methods)
Socket.send method: Sends data to a connected Socket from the indicated position in the data.
public int Send (byte[], int, socketflags);(overloaded method)
The Socket.sendto method sends data to a specific endpoint.
public int SendTo (byte[], EndPoint) (with overloaded methods)
Socket.receive method: Receives data from the connected Socket to a specific location in the receive buffer.
public int Receive (byte[],int,socketflags);
Socket.receivefrom method: Receives data from a specific location in the data buffer and stores endpoints.
public int ReceiveFrom (byte[], int, socketflags, ref EndPoint);
Socket.bind method: Causes the Socket to be associated with a local endpoint:
public void Bind (EndPoint localep);
Socket.listen method: Places the Socket on the listening state.
public void Listen (int backlog);
Socket.accept method: Creates a new Socket to handle incoming connection requests.
Public Socket Accept ();
Socket.shutdown method: Disable send and receive on a Socket
public void Shutdown (SocketShutdown);
Socket.close method: Force the Socket connection to close
public void close ();


As you can see, many of these methods contain parameters for the endpoint type, in which 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.

When using the IPEndPoint class, it inevitably involves the IP address of the computer. NET has two kinds to get an IP address instance:

IPAddress class: The IPAddress class contains the address of the computer on the IP network. Its Parse method converts an IP address string to an IPAddress instance. The following statement creates a IPAddress instance:

IPAddress MyIP = Ipaddress.parse ("192.168.1.2");


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 "host.contoso.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 following code gets a IPAddress instance that contains the IP address of the server host.contoso.com.

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


You can also use the GetHostName method to get the Iphostentry instance:

Iphosntentry hostinfo=dns.gethostbyname ("host.contoso.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

After mastering the above knowledge, the following code combines the server host (Host.contoso.com's IP address and port number to create a remote endpoint for the connection:

IPEndPoint ipe = new IPEndPoint (ipaddress,11000);

Current 1/2 page 12 Next read the full text
Related Article

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.