A study on C # 2.0 socket Programming Example

Source: Internet
Author: User
Tags bind socket port number

First of all, the principle of the use of Socket Interface network communication, here to the most commonly used C/s mode as an example, first of all, the server has a process (or multiple processes) at the specified port waiting for customers to connect, the service program waiting for the customer's connection information, once connected, Data can be transmitted according to the method and format of the design. The client issues a connection request to the server at the required time. Here, for the sake of understanding, some calls and their approximate functions are mentioned. After using the socket call, only one socket descriptor can be used, which cannot be communicated, and other calls are made so that the information used in the structure referred to by the socket is filled out.

When using the TCP protocol, the General Service-side process first uses the socket call to get a descriptor and then joins a name with the socket descriptor using the bind call, which is to connect the Internet address to the socket for the Internet domain. The service side then uses the listen call to indicate the length of the Wait service request queue. You can then use the accept call to wait for the client to initiate a connection, typically blocking the wait connection, and once a client issues a connection, accept returns the customer's address information and returns a new socket descriptor that has the same characteristics as the original socket. The server can then use this new socket for read and write operations. The General Service side may create a new process to communicate with the customer after accept returns, and the parent process waits for another connection at the accept call. The client process typically uses a socket call to get a socket descriptor, then uses connect to initiate a connection to the specified port on the specified server, and once the connection is successfully returned, the connection to the server is established, and the socket descriptor is used to read and write.

. NETFramework provides a System.Net.Socket namespace for socket communication, in which there are several important classes that are commonly used:

· Socket class This low-level class is used to manage connections, and webrequest,tcpclient and UdpClient use this class internally.

· NetworkStream class This class is derived from the stream, which represents the flow of data from the network

· TcpClient class allows TCP connections to be created and used

· TcpListener class allows incoming TCP connection requests to be monitored

· UdpClient class for UDP client creation connections (UDP is another TCP protocol, but not widely used, primarily for local networks)

Let's look at a C # version of the two-machine communication code based on the socket

You first create an instance of the socket object, 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 temp = 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 temp = 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 (you can initiate the connection at the Connect method before the bind port, or on the specified port, if you do not bind the port number beforehand. The system defaults to 1024 to 5000 randomly binding a port number and sends data to the remote server via the Send method, which can then receive data from the server via receive; 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, close the socket with the closing method.

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 the IPEndPoint class is used, it inevitably involves the IP address of the computer, and there are two kinds of system.net namespaces that can 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.0.1");

What you need to know is that the Socket class supports two basic modes: synchronous and asynchronous. The difference is that in synchronous mode, a block is transferred, and calls to functions that perform network operations, such as Send and Receive, wait until all content transfer operations have completed before returning control to the caller. In asynchronous mode, a bitwise transfer requires specifying the start and end of the send. Synchronization mode is the most common pattern, and our example here is the use of synchronous mode.

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.