C #. NET network program development-socket Article _ C # Application

Source: Internet
Author: User

I think this article's introduction to socket is easy to understand.

Source: http://www.west263.com/www/info/59554-1.htm

Microsoft. net Framework provides applications with hierarchical, scalable, and governed network services to access the Internet. Its namespace is system. net and system. net. sockets contains a variety of classes to develop a variety of network applications .. . Net class uses a layered structure that allows applications to access the network at different control levels. developers can choose to compile programs at different levels as needed, these levels cover almost all the needs of the Internet-from socket sockets to common requests/responses. More importantly, this layer can be expanded to meet the needs of continuous Internet expansion.

Aside from the layer-7 architecture of the ISO/OSI model, we can look at the logic layer of the TCP/IP model ,. net class can be considered to contain three layers: Request/response layer, application protocol layer, and transmission layer. Webreqeust and webresponse represent the request/response layer. Classes supporting HTTP, TCP, and UDP constitute the application protocol layer, while the socket class is in the transmission layer.

The transport layer is located at the bottom of this structure. When the application protocol layer and request/response layer above cannot meet the special needs of applications, you need to use this layer for Socket socket programming.

In. net, the system. net. Sockets namespace provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to strictly control network access. System. all other network protocol classes in the. NET namespace are built on the socket implementation. For example, tcpclient, tcplistener, and udpclient encapsulate detailed information about TCP and UDP connections created to the Internet; the networkstream class provides basic data streams for network access. Many common Internet services can see socket traces, such as telnet, HTTP, email, and echo, despite the different definitions of the communication protocol, the basic transmission of these services uses sockets.

In fact, the socket can be considered as a data channel like a stream. This channel is set up between the application end (client) and the remote server end, and then reads (receives) data) and write (send) for this channel.

It can be seen that after a socket object is created on the application or server, you can use the send/sentto method to send data to the connected socket, alternatively, use the receive/receivefrom method to receive data from the connected socket;

For socket programming, the socket class of the. NET Framework is the managed code version of the socket service provided by the winsock32 API. A large number of methods are provided for network programming. In most cases, the socket class method only sends data to their local Win32 copies and handles any necessary security checks. If you are familiar with Winsock API functions, it will be very easy to write network programs using the socket class. Of course, if you have never been in touch with it, it will not be too difficult. Follow the instructions below, you will find that there are rules to develop Windows network applications using the socket class, which follow roughly the same steps in most cases.

Before using it, you must first create an instance of the socket object, which can be achieved through the socket class constructor:

Public socket (addressfamily, sockettype, protocoltype );

The addressfamily parameter specifies the addressing scheme used by the socket, The sockettype parameter specifies the socket type, and the protocoltype parameter specifies the protocol used by the socket.

The following example creates a socket that can be used for communication over TCP/IP-based networks (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 a socket is created on the client, you can connect to the specified server through the connect method and send data to the remote server through the send/sendto method, then, you can use receive/receivefrom to receive data from the server. on the server side, you need to bind the specified interface using the bind method to associate the socket with a local endpoint, the listen method is used to listen for requests on this interface. When listening for a connection to the user end, the accept is called to complete the connection operation, and a new socket is created 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 methods/functions used in this process include:

Socket. Connect Method: establish a connection to a remote device
Public void connect (endpoint remoteep) (with overload method)
Socket. Send method: sends data to the connected socket starting from the indicated position in the data.
Public int send (byte [], Int, socketflags); (there are overload methods)
The socket. sendto method sends data to a specific endpoint.
Public int sendto (byte [], endpoint); (there are overload methods)
Socket. Receive method: receives data from the connected socket to a specific location in the receiving buffer.
Public int receive (byte [], Int, socketflags );
Socket. receivefrom method: receives data from a specific location in the data buffer and stores the endpoint.
Public int receivefrom (byte [], Int, socketflags, ref endpoint );
Socket. Bind method: Associate the socket with a local endpoint:
Public void BIND (endpoint localep );
Socket. Listen method: place the socket in the listening state.
Public void listen (INT backlog );
Socket. Accept method: Create a new socket to process incoming connection requests.
Public socket accept ();
Socket. Shutdown method: Disable sending and receiving on a socket
Public void Shutdown (socketshutdown how );
Socket. Close method: Force socket connection to close
Public void close ();

As you can see, the preceding methods contain endpoint parameters. On 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 a specific service on the device to be connected. The combination of network addresses and service ports is called an endpoint. in the. NET Framework, the endpoint class indicates the endpoint. It provides an abstraction that represents network resources or services and marks network addresses and other information .. Net also defines the child of an endpoint for each supported address family. For an IP address family, this class is ipendpoint. The ipendpoint class contains the host and port information required by the application to connect to the service on the host. The ipendpoint class forms a connection point to the service by combining the Host IP address and port number of the service.

When using the ipendpoint class, it inevitably involves the computer ip address. There are two types of. net IP address instances:

IPaddress: The IPaddress class contains the IP address of the computer on the IP network. The 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: Provides domain name services to applications that use TCP/IP Internet services. Its resolve method queries DNS servers to map user-friendly Domain Names (such as "host.contoso.com") to digital Internet addresses (such as 192.168.1.1 ). The resolve method returns an iphostenty instance that contains a list of the addresses and aliases of the requested names. In most cases, you can use the first address returned in the Addresslist array. The following code obtains an IPaddress instance that contains the IP address of host.contoso.com.

Iphostentry iphostinfo = DNS. Resolve ("host.contoso.com ");
IPaddress = iphostinfo. Addresslist [0];

You can also use the gethostname method to obtain the iphostentry instance:

Iphosntentry hostinfo = DNS. gethostbyname ("host.contoso.com ")

When using the preceding methods, you may need to handle the following exceptions:

Socketexception exception: the operating system error occurs when the socket is accessed.

Argumentnullexception exception: the parameter is null.

Objectdisposedexception exception: the socket has been closed.

After learning the above knowledge, the following code combines the IP address and port number of the server host (host.contoso.com) to create a remote endpoint for the connection:

Ipendpoint IPE = new ipendpoint (IPaddress, 11000 );

After the address of the remote device is determined and the port used for connection is selected, the application can try to establish a connection with the remote device. The following example uses an existing ipendpoint instance to connect to a remote device and capture Possible exceptions:

Try {
S. Connect (IPE); // try to connect
}
// An exception occurred when the processing parameter is null.
Catch (argumentnullexception AE ){
Console. writeline ("argumentnullexception: {0}", AE. tostring ());
}
// Handle operating system exceptions
Catch (socketexception SE ){
Console. writeline ("socketexception: {0}", se. tostring ());
}
Catch (exception e ){
Console. writeline ("unexpected exception: {0}", E. tostring ());
}

You need to know that the socket class supports two basic modes: synchronous and asynchronous. The difference is that in synchronous mode, the call to the function that executes network operations (such as send and receive) will not return the control to the caller until the operation is complete. In asynchronous mode, these calls return immediately.

In addition, in many cases, socket programming is implemented on the client and server based on different situations, and the application program is compiled on the client to send requests to the specified port on the server, at the same time, the preparation of the server application to process the request has been mentioned in the above description; of course, not all socket programming requires you to strictly write these two programs; depending on the application situation, you can construct a request string on the client. The corresponding port of the server captures the request and submits it to its public service program for processing. The string in the following example sends a page request to the remote host:

String get = "Get/HTTP/1.1 \ r \ nhost:" + SERVER + "\ r \ nconnection: Close \ r \ n ";

After the specified port of the remote host receives this request, it can use its public service program for processing without the need to compile server applications separately.

Using the knowledge of using Visual C # For Socket network program development described above, the program section below fully implements the web page download function. You only need to enter the remote host name (DNS host name or IP address in four-part notation separated by dots) and the pre-saved local file name on the form, the remote host page can be obtained and saved in the specified file on the local machine by using port 80 that provides the HTTP service. If the format is .htm, you can open the page in an Internet browser. Add code as appropriate, and you can even implement a simple browser program.

The main source code for implementing this function is as follows:

// "Start" button event
Private void button#click (Object sender, system. eventargs e ){
// Obtain the pre-saved file name
String filename = textbox3.text. Trim ();
// Remote host
String hostname = textbox1.text. Trim ();
// Port
Int Port = int32.parse (textbox2.text. Trim ());
// Obtain host information
Iphostentry ipinfo = DNS. gethostbyname (hostname );
// Obtain IPaddress []
IPaddress [] ipaddr = ipinfo. Addresslist;
// Obtain the IP address
IPaddress IP = ipaddr [0];
// Combine remote endpoints
Ipendpoint hostep = new ipendpoint (IP, Port );
// Create a socket instance
Socket socket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Try
{
// Try to connect
Socket. Connect (hostep );
}
Catch (exception SE)
{
MessageBox. Show ("connection error" + Se. message, "prompt message
, Messageboxbuttons. retrycancel, messageboxicon. information );
}
// Request content string sent to the remote host
String sendstr = "Get/HTTP/1.1 \ r \ nhost:" + hostname +
"\ R \ nconnection: Close \ r \ n ";
// Create a bytes byte array to convert the sending string
Byte [] bytessendstr = new byte [1, 1024];
// Convert the sent content string to a byte array
Bytessendstr = encoding. ASCII. getbytes (sendstr );
Try
{
// Send a request to the host
Socket. Send (bytessendstr, bytessendstr. length, 0 );
}
Catch (exception CE)
{
MessageBox. Show ("sending error:" + Ce. message, "prompt message
, Messageboxbuttons. retrycancel, messageboxicon. information );
}
// Declare the string that receives the returned content
String recvstr = "";
// Declare a byte array. The length of data received at a time is 1024 bytes.
Byte [] recvbytes = new byte [1, 1024];
// Returns the actual number of bytes of received content.
Int bytes = 0;
// Read data cyclically until all data is received
While (true)
{
Bytes = socket. Receive (recvbytes, recvbytes. length, 0 );
// Exit the loop after reading.
If (Bytes <= 0)
Break;
// Convert the number of bytes read to a string
Recvstr + = encoding. ASCII. getstring (recvbytes, 0, bytes );
}
// Convert the read string to a byte array
Byte [] content = encoding. ASCII. getbytes (recvstr );
Try
{
// Create a file stream object instance
Filestream FS = new filestream (filename, filemode. openorcreate, fileaccess. readwrite );
// Write a file
FS. Write (content, 0, content. Length );
}
Catch (exception Fe)
{
MessageBox. Show ("file creation/writing error:" + Fe. message, "prompt message", messageboxbuttons. retrycancel, messageboxicon. information );
}
// Disable socket
Socket. Shutdown (socketshutdown. Both );
// Close the socket
Socket. Close ();
}
}

The program is successfully debugged under the Windows XP Chinese version,. NET Framework Chinese official version, and Visual Studio. NET Chinese official version.

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.