TCP-UDPTCP-UDP

應用程式可以使用「傳輸控制通訊協定 (TCP)」和「使用者資料包通訊協定 (UDP)」服務,搭配 TcpClientTcpListenerUdpClient 類別。Applications can use Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) services with the TcpClient, TcpListener, and UdpClient classes. 這些通訊協定類別建立在 System.Net.Sockets.Socket 類別之上,並負責傳送資料的細節。These protocol classes are built on top of the System.Net.Sockets.Socket class and take care of the details of transferring data.

通訊協定類別使用 Socket 類別的同步方法,以提供簡單且直接的網路服務存取,不需要維護狀態資訊或了解設定通訊協定特定通訊端的詳細資料等成本。The protocol classes use the synchronous methods of the Socket class to provide simple and straightforward access to network services without the overhead of maintaining state information or knowing the details of setting up protocol-specific sockets. 若要使用非同步 Socket 方法,您可以使用 NetworkStream 類別所提供的非同步方法。To use asynchronous Socket methods, you can use the asynchronous methods supplied by the NetworkStream class. 若要存取 Socket 類別中通訊協定類別未公開的功能,您必須使用 Socket 類別。To access features of the Socket class not exposed by the protocol classes, you must use the Socket class.

TcpClientTcpListener 代表使用 NetworkStream 類別的網路。TcpClient and TcpListener represent the network using the NetworkStream class. 您使用 GetStream 方法來傳回網路資料流,然後呼叫資料流的 ReadWrite 方法。You use the GetStream method to return the network stream, and then call the stream's Read and Write methods. NetworkStream 並未擁有通訊協定類別的基礎通訊端,因此關閉它並不會影響通訊端。The NetworkStream does not own the protocol classes' underlying socket, so closing it does not affect the socket.

UdpClient 類別使用位元組陣列來保留 UDP 資料包。The UdpClient class uses an array of bytes to hold the UDP datagram. 您使用 Send 方法將資料傳送到網路,及使用 Receive 方法來接收連入的資料包。You use the Send method to send the data to the network and the Receive method to receive an incoming datagram.

另請參閱See also