Author: Song Hua www.ASPCool.com Microsoft.Net Framework for the application to access the Internet provides a hierarchical, scalable network services and governed by, the System.Net namespace contains a wealth of class and System.Net.Sockets A variety of web applications can be developed. The hierarchical structure adopted by the .NET class allows the application to access the network at different levels, developers can choose to make different levels of programming as needed, almost all incorporated all needs - from Socket sockets Ordinary request / response, more importantly, this hierarchy can be extended and can adapt to the need for Internet's continuous expansion. The 7-layer architecture of the ISO / OSI model is thrown from the logical level on the TCP / IP model. The .NET class can be considered to include 3 levels: request / response layer, application protocol layer, transport layer. WebReQEUST and WebResponse represent the request / response layer, which supports HTTP, TCP, and UDP classes that form the application protocol layer, while the Socket class is in the transport layer. It can be illustrated below: It can be seen that the transport layer is located at the bottom of this structure. When the above application protocol layer and the request / response layer do not meet the specific needs of the application, it is necessary to use this layer to perform Socket socket programming. In .NET, System.Net.Sockets namespace provides a managed implementation of a Windows Sockets (Winsock) interface for developers who need to strictly control network access. All other network access classes in the System.Net Namespace are built on the socket socket implementation, such as TCPClient, TCPListener, and UDPClient class packages for more information on creating TCPs and UDP connections to the Internet; NetworkStream class provides The basic data stream of network access, etc., all of the common Internet services can see the traces of sockets, such as Telnet, HTTP, Email, Echo, etc. These services although the communication protocol protocol definition is different, its basic transmission is adopted. Socket. In fact, Socket can be considered as a data channel as a stream stream. This channel is set between the application terminal (client) and the remote server side, and the data read (reception) and write (send) are targeted This channel is carried out. It can be seen that after the application end or the server side creates a socket object, 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 the socket, .NET framework The Socket class is a managed code version of the socket service provided by the Winsock32 API. Some of them provide a large number of methods for realizing network programming, in most cases, the Socket class method is just to send data to their local WIN32 copies and handle any necessary security checks. If you are familiar with the Winsock API function, you will be very easy to write a web program with the Socket class. Of course, if you have never touched, it will not be too difficult. Follow the following explanation, you will find that using the Socket class development Windows network application originally Regulations, they follow the substantially the same steps in most cases.
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, SocketType The parameter specifies the type of socket, the protocoltype parameter specifies the protocol used by the socket. The following sample statement creates a socket, which can be used to communicate on a TCP / IP network (such as the Internet). Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); to use UDP instead of the TCP, need to change the protocol type, as in the following example: Socket s = new Socket (AddressFamily.InterNetwork, SocketType .Dgram, protocoltype.udp); Once you create a socket, on the client, 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, and then receive from the server from the server via Receive / ReceiveFrom Data; on the server side, you need to use the bind method to bind the specified interface to make the socket associated with a local endpoint and listen to the request on the interface through the Listen method. When listening to the user's connection, call Accept completes the operation of the connection, creates a new socket to process incoming connection requests. After using the socket, remember to use the shutdown method to disable the socket and use the Close method to close the Socket. The method / functions used thereto are: socket.connect method: establish a connection to remote device PUBLIC VOID Connect (Endpoint Remoteep) Socket.send method: Send data to the connection from the indication position in the data Socket. Public int send (Byte [], int, socketflags; (have an overload method) socket.sendto method sends data to a specific endpoint. PUBLIC INT sentto (Byte [], EndPoint); (with overloaded method) Socket.Receive method: Receive data from the connected socket to a particular location of the received buffer. Public int received (Byte [], int, socketflags; socket.ReceiveFrom method: Receive data of a specific location in the data buffer and store endpoints. Public int respientFrom (Byte [], int, socketflags, ref endpoint); socket.bind method: Make Socket associated with a local endpoint: public void bind; socket.listen method: Place Socket in listening status. Public void listen; socket.accept method: Create a new Socket to process incoming connection requests.
Public socket accept (); socket.shutdown method: Disable send and receive public void shutdown (socketShutdown how) on a socket; Socket.Close method: Force Socket connection to close public void close (); can be seen, many of the above methods EndPoint type parameters, in the 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. When you use the IPENDPOINT class, you will inevitably involve computer IP addresses, two classes in .NET can get an IP address instance: ipaddress class: The iPadDress class contains the address on the IP network. Its PARSE method can convert an IP address string to an iPadDress instance. The following statement creates an ipaddress instance: ipaddress myip = ipaddress.parse ("192.168.1.2"); 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 "host.contoso.com" to the digital form of Internet addresses (eg 192.168.1.1). The resolve method returns an iPhostenty instance that contains the list of addresses and aliases of the requested name. In most cases, you can use the first address returned in the AddressList array. The following code acquires an 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 get IPHostEntry instance GetHostName method: IPHosntEntry hostInfo = Dns.GetHostByName ( "host.contoso.com" When using the above method, you may need to handle the following exception: Socketexception error: Error incorrectly occurring when accessing socket: The parameter is an empty reference to trigger the ObjectDisposedException exception: Socket has been turned off to master the top knowledge, The following code will combine the server host (Host.Contoso.com with port number to create remote endpoints for connectivity: IpendPoint IPE = New IpendPoint (iPaddress, 11000); determined the address of the remote device and selected After the connection is connected, the application can attempt to establish a connection with the remote device. The following example uses an existing IpendPoint instance to connect with the remote device and capture the possible exception: try {s.connect (IPE); // Try Connection} // Process parameters are empty reference exception Catch (argumentnullexception ae) {console.writeLine ("Argumentnullexception: {0}", ae.tostring ());} // Handling Operating System Exception Catch (Socketexception SE) {Console. WriteLine ("socketexception: {0}", se.tostring ());} catch (exception e) {console.writeline ("Unexpected Exception: {0}", E.TOSTRING ());} You need to know: Socket class supports two basic modes: Synchronization And asynchronously. 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. In addition, many times, Socket programming needs to be implemented separately on the client and server side, and sends a request to the server to the server, and the server application processing the request, this process is above It has been mentioned in the elaboration; of course, not all socket programming requires you to strictly write these two-end program; depending on the application situation, you can construct a request string in the client, and the server corresponding port captures this request. The service program is processed.
The string in the following example statement provides a page request to the remote host: string get = "Get / http / 1.1 / r / nhost:" Server "/ r / nConnection: Close / R / N / R / N"; Once the remote host specifies that the port is accepted, it can be processed using its public service program without requiring another server-side application. Comprehensively use the knowledge of the use of Visual C # to develop Socket network program, the following program segment fully implements the web page download function. Users only need to enter remote hostnames (DNS hostnames or IP addresses with point-separated four-part indication formats) and pre-saved local file names, and take advantage of 80 ports that specifically provide HTTP services. The remote host page is saved in the local specified file. If the save format is .htm format, you can open this page in the Internet browser. Adding a code properly, you can even implement a simple browser program.
The main source code for this feature is as follows: // "Start" button event private void button1_click (object sender, system.eventargs e) {// get pre-saved file name string filename = textBox3.Text.trim (); // Remote host string hostname = textbox1.text.trim (); // port int port = int32.parse (TextBox2.Text.trim ()); // Get host information iphostentry ipinfo = dns.gethostbyname (Hostname); // Ipaddress [] ipaddress [] ipaddr = ipinfo.addresslist; // Get IP ipaddress ip = ipaddr [0]; // Combine remote endpoint iPENDPOINT HOSTEP = New IpendPoint (IP, port); // Create a Socket instance socket socket = New socket (addressFamily.internetwork, sockettype.internet, protocoltype.tcp); try {// Try connecting socket.connect (hostep);} catch (exception se) {messagebox.show ("Connection error" se.Message, " Tip information, MessageBoxButtons.Retrycancel, MessageBoxicon.information;} // Send String SendStr = "Get / Hostname " / R / NCONNECTION: CLOSE / R / n / r / n "; // Create a BYTES byte array to convert the sending string byte [] bytessendstr = new byte [1024]; // will send a content string to convert into byte byte array bytessendstr = Encodi ng.ascii.getbytes (sendStr); Try {// Send a request socket.send (bytessendstr, bytessendstr.length, 0);} catch ("send error:" ce.SHOW ("Send Error:" CE.MESSAGE , "Tips Information, MessageBoxButtrycancel, MessageBoxicon.information);} // Declaration Receive String String RCVSTR =" "; // A declaration byte array, the length of the received data is 1024 bytes byte [] recvbytes = New Byte [1024]; // Returns the number of bytes of actual reception content INT BYTES = 0; // Recycling Read until all data while (true) {bytes = socket.Receso (Recvbytes, Recvbytes.length, 0); // After reading the completion, exit the cycle IF (Bytes <= 0) Break; // Convert the number of bytes of the read to a string RECVSTR =