Visual C #. Net network program development-Tcp

Source: Internet
Author: User
Tags getstream

Author: Song Hua
Previous Article Visual C #. net network program development-Socket: classes that support Http, Tcp, and Udp form a layer-3 TCP/IP model (Request Response layer, application protocol layer, and Transport Layer) the middle layer-application protocol layer. The analogy of this layer is located at the bottom layer of the Socket class to provide a higher level of abstraction. They encapsulate the creation of TCP and UDP sockets and do not need to process the connection details, this allows us to use more TCPClient, UDPClient, and TcpListener when writing Socket-level protocols, rather than writing them directly to the Socket. The hierarchical relationship between them is shown as follows:

It can be seen that the TcpClient class is built based on the Socket class, which is the foundation for providing TCP services with a higher degree of abstraction. Because of this, many communication protocols on the application layer, such as the File transfer Protocol (FTP) and HTTP (Hypertext Transfers Protocol) hypertext Transfer Protocol is directly created on TcpClient and other classes.

The TCPClient class uses TCP to request data from Internet resources. Establish a connection with the remote endpoint over TCP, and then use this connection to send and receive data packets. TCP is responsible for ensuring that packets are sent to the end point and combined in the correct order when the packets arrive.

From the name, we can see that the TcpClient class is designed for clients and provides client connections for TCP network services. TcpClient provides a simple method to connect, send, and receive data over a network.

To establish a TCP connection, you must know the IP address of the network device that hosts the required service and the TCP Port used for communication ). Internet Assigned Numbers Authority (IANA) defines the port number of the Public Service (you can access http://www.iana.org/assignments/port-numbers for more detailed information ). Services not in the IANA list can use port numbers in the range of 1,024 to 65,535. To create such a connection, you can use one of the three constructors of the TcpClient class:

1. public TcpClient () when using this constructor without any parameters, the default IP address of the local machine is used and the default communication port number is 0. In this case, if there is more than one IP address on the local machine, you cannot choose to use it. The following statement demonstrates how to use the default constructor to create a new TcpClient:

TcpClient tcpClientC = new TcpClient ();


2. public TcpClient (IPEndPoint) uses the local IPEndPoint to create a TcpClient instance object. As described in the previous article, IPEndPoint represents the network endpoint as an IP address and port number. Here it is used to specify the local network interface (IP address) and port number used to establish a remote host connection, this constructor provides a choice for using the local IPAddress and Port. The following statement demonstrates how to use a local endpoint to create a TcpClient class instance:

IPHostEntry ipInfo = Dns. GetHostByName ("www.tuha.net"); // host information
IPAddressList [] ipList = ipInfo. AddressList; // ip address Array
IPAddress ip = ipList [0]; // The first ip address is usually used for multiple ip addresses.
IPEndPoint ipEP = new IPEndPoint (ip, 4088); // obtain the network endpoint
Try {
TcpClient tcpClientA = new TcpClient (ipLocalEndPoint );
}
Catch (Exception e ){
Console. WriteLine (e. ToString ());
}


At this point, you may be confused. The client needs to create a connection with the server. The specified IP address and communication port number should be from the remote server! In fact, with the above two constructor, all you need to do is bind the TcpClient instance object to the IP address and Port to complete the connection, you also need to explicitly specify the connection to the remote host, which can be achieved through the TcpClient Connect method. The Connet method uses the specified host name and port number to Connect the client to the remote host:

1) public void Connect (IPEndPoint); Use the specified remote network endpoint to Connect the client to the remote TCP host.

Public void Connect (IPAddress, int); Connect the client to the TCP host using the specified IP address and port number.

Public void Connect (string, int); connects the client to the specified port on the specified host.

It should be noted that the IPEndPoint network endpoint parameter in all the reloads of the Connect Method

Node, IPAddress, And the Dns host name and Port pointed out by int indicate the remote server.

The following example uses the default Host IP address and Port number 0 to establish a connection with the remote host:

TcpClient tcpClient = new TcpClient (); // create a TcpClient object instance
Try {
TcpClient. Connect ("www.contoso.com", 11002); // establish a connection
}
Catch (Exception e ){
Console. WriteLine (e. ToString ());
}


3. public TcpClient (string, int); initialize a new instance of the TcpClient class and connect it to the specified port on the specified host. Unlike the first two constructors, this constructor automatically establishes a connection and you do not need to call the Connect method. The string type parameter indicates the Dns name of the remote host, for example, www.tuha.net.

The following example calls this method to connect to the host with the specified host name and port number:

Try {
TcpClient tcpClientB = new TcpClient ("www.tuha.net", 4088 );
}
Catch (Exception e ){
Console. WriteLine (e. ToString ());
}

As we mentioned above, the TcpClient class is created on the Socket and provides a higher level of abstraction in the Tcp Service, which is reflected in the transmission and acceptance of network data, tcpClient uses the standard Stream processing technology to make it easier and more intuitive to read and write data ,. the. Net Framework is responsible for providing richer structures for stream processing throughout the entire process. the stream in the. Net Framework has wider compatibility, the general method built on more general stream operations makes us no longer need to be confused with the actual content of the file (HTML, XML, or any other content ), all applications will use the same method (Stream. write, Stream. read) sends and receives data. In addition, the stream provides real-time access to data when data is downloaded from the Internet. You can process some data immediately when it arrives without waiting for the application to download the complete dataset .. Net implements these processing technologies through the NetworkStream class.

The NetworkStream class is included in the System. Net. Sockets namespace Of the. Net Framework. This class provides basic data streams for network access. NetworkStream provides a standard. Net Framework Stream Mechanism for sending and receiving data through network sockets. NetworkStream supports synchronous and asynchronous access to network data streams. NetworkStream inherits from Stream, which provides a rich set of methods and attributes for convenient network communication.

Like all other streams inherited from the abstract base-class Stream, NetworkStream network streams can also be considered as a data channel between the data source end (customer Client) and the receiving end (Service Server, the subsequent data reading and writing are based on this channel.

In the. Net Framework, NetworkStream supports two operations:

1. Write a stream. Write data is transmitted from the data structure to the stream.

Schematic diagram


2. Read the stream. Read data is transmitted from the stream to the data structure (such as byte arrays.

Schematic diagram

Different from a normal Stream, a network Stream does not have a uniform concept of the current position. Therefore, it does not support searching and random access to data streams. The corresponding attribute CanSeek always returns false, and the Seek and Position Methods also lead to NotSupportedException.

For Socket-based application protocols, you can obtain NetworkStream network data streams in the following two ways:

1. Use the NetworkStream constructor: public NetworkStream (Socket, FileAccess, bool); (there are overload methods ), it uses the specified access permission and the specified Socket permission to create a new NetworkStream class instance for the specified Socket. before using it, you need to create a Socket object instance and use the Socket. the Connect method establishes a connection with the remote server before you can use this method to obtain the network transmission stream. Example:

Socket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp); // create a client Socket object instance
Try {
S. Connect ("www.tuha.net", 4088); // establish a connection with the remote host
}
Catch (Exception e ){
MessageBox. show ("connection error:" + e. Message );
}
Try {
NetworkStream stream = new NetworkStream (s, FileAccess. ReadWrite, false); // obtain the network transmission stream
}


2. Use the TcpClient. GetStream method: public NetworkStream etStream (); it returns the NetworkStream of the basic network stream used to send and receive data. GetStream uses the basic Socket as its constructor parameter to create an instance of the NetworkStream class. Before using TcpClient, you need to create a TcpClient object instance and establish a connection with the remote host, for example:

TcpClient tcpClient = new TcpClient (); // create a TcpClient object instance
Try {
TcpClient. Connect ("www.tuha.net", 4088); // try to Connect to the remote host
}
Catch (Exception e ){
MessageBox. Show ("connection error:" + e. Message );
}
Try {
NetworkStream stream = tcpClient. GetStream (); // gets the network transmission stream
}
Catch (Exception e)
{
MessageBox. Show ("TcpClient error:" + e. Message );
}


After obtaining the NetworkStream network stream through the above method, you can use the standard stream Read/Write method Write and Read to send and accept data.

The above is. net, in order to provide these services to the client, we also need to compile the corresponding server program, the previous article "Visual C #. net network program development-Socket mentioned above that Socket, as the basis of other network protocols, can be used for both client-side development and server-side development, and is widely used in the transmission layer, on the application protocol layer, we use TcpClient built on the Socket class to replace the Socket. Correspondingly, TcpListener built on the Socket provides a higher level of TCP Service, this makes it easier for us to write server applications. For this reason, application layer protocols such as FTP and HTTP are built on the basis of the TcpListener class.

. The TCPListener in. Net is used to monitor incoming requests on the TCP port and create a TcpListener object instance by binding the local IP address and the corresponding port (the two must be consistent with the client request, start the listener by using the Start method. When TcpListener listens to the connection to the client, it uses AcceptTcpClient based on different request methods of the client.

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.