TcpClient 為 TCP 網路服務提供用戶端串連。
System.Object
System.Net.Sockets.TcpClient
[C#]public class TcpClient : IDisposable
備忘
TcpClient 類提供了一些簡單的方法,用於在同步阻塞模式下通過網路來串連、發送和接收流資料。
為使 TcpClient 串連並交換資料,使用 TCP ProtocolType 建立的 TcpListener 或 Socket 必須偵聽是否有傳入的串連請求。可以使用下面兩種方法之一串連到該接聽程式:
- 建立一個 TcpClient,並調用三個可用的 Connect 方法之一。
- 使用遠程主機的主機名稱和連接埠號碼建立 TcpClient。此建構函式將自動嘗試一個串連。
注意 如果要在同步阻塞模式下發送無串連資料報,請使用 UdpClient 類。
對繼承者的說明: 要發送和接收資料,請使用 GetStream 方法來擷取一個 NetworkStream。調用 NetworkStream 的 Write 和 Read 方法與遠程主機之間發送和接收資料。使用 Close 方法釋放與 TcpClient 關聯的所有資源。
樣本 C#下面的樣本建立
TcpClient 串連。
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}