Applications can use the Transmission Control Protocol (TCP) and user data packet protocol (UDP) services through TCPClient, TCPListener, and UDPClient. These protocol classes are based on the System. Net. Sockets. Socket class, responsible for data transmission details. (TCPClient, TCPListener, and UDPClient are used to simplify Socket)
TcpClient and TcpListener use the NetworkStream class to represent the network. Use the GetStream method to return the network stream, and then call the Read and Write methods of the stream. NetworkStream does not have a basic socket for the Protocol class, so disabling it does not affect the socket.
The UdpClient class uses byte arrays to save UDP data packets. Use the Send method to Send data to the network, and use the Receive method to Receive incoming data packets.
1. TcpClient
The TcpClient class provides some simple methods for connecting, sending, and receiving stream data through the network in synchronous blocking mode. To enable TcpClient to connect and exchange data, the TcpListener or Socket created using TCP ProtocolType must listen for incoming connection requests. You can use either of the following two methods to connect to the listener:
(1) create a TcpClient and call one of the three available Connect methods.
(2) create a TcpClient using the host name and port number of the remote host. This constructor will automatically try a connection.
To send and receive data to the successor, use the GetStream method to obtain a NetworkStream. Call the Write and Read methods of NetworkStream to send and receive data between the remote host. Use the Close method to release all resources associated with TcpClient.
The following example shows how to use TcpClient to connect to the server:
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Net. Sockets;
Using System. Net;
Namespace tcpclient
{
Class Program
{
Private static int portnum= 11000;
Private static string hostName = Dns. GetHostName (). ToString ();
Public static void Main (String [] args)
{
Try
{
Console. WriteLine ("Host Name:" + Dns. GetHostName ());
Console. WriteLine ("Host IP Address:" + Dns. GetHostAddresses (Dns. GetHostName () [0]);
TcpClient client = new TcpClient (hostName, portNum );
NetworkStream ns = client. GetStream ();
Byte [] bytes = new byte [1, 1024];
Int bytesRead = ns. Read (bytes, 0, bytes. Length );
// Decodes byte streams into strings
Console. WriteLine (Encoding. ASCII. GetString (bytes, 0, bytesRead ));
Client. Close ();
}
Catch (