TCP(Transmission Control Protocol)是網路世界的基石,HTTP、FTP、SMTP 等應用層協議皆建構於 TCP 之上。掌握 TCP 程式設計,即掌握了網路通訊的核心邏輯。雖然 TCP 內部機制複雜(三向交握、滑動視窗、擁塞控制等),但在 .NET Framework 的加持下,開發者無需深究底層細節,即可輕鬆撰寫高效穩定的網路應用程式。
.NET 在 System.Net.Sockets 命名空間提供兩個關鍵類別:
NetworkStream 進行資料流讀寫。TcpClient 實例進行後續通訊。我們將建立一個經典的「時間伺服器」範例,包含伺服器端與用戶端兩個獨立程式。伺服器監聽埠號 13,用戶端連線後立即取得伺服器當前時間。
using System;
using System.Net.Sockets;
using System.Text;
namespace TcpClientExample
{
public class TcpTimeClient
{
private const int Port = 13;
private const string Host = "127.0.0.1";
public static void Main()
{
try
{
Console.WriteLine($"正在連線至 {Host}:{Port} ...");
// 建立連線並取得資料流
using (TcpClient client = new TcpClient(Host, Port))
using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string serverTime = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"伺服器時間:{serverTime}");
}
}
catch (Exception ex)
{
Console.WriteLine($"發生錯誤:{ex.Message}");
}
Console.ReadLine(); // 暫停畫面以便觀察結果
}
}
}
using System;
using System.Net.Sockets;
using System.Text;
namespace TimeServer
{
class Program
{
private const int Port = 13;
static void Main(string[] args)
{
TcpListener listener = new TcpListener(Port);
listener.Start();
Console.WriteLine($"時間伺服器已啟動,正在埠號 {Port} 監聽...");
while (true)
{
Console.Write("等待用戶端連線...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("連線已建立。");
try
{
using (NetworkStream stream = client.GetStream())
{
string currentTime = DateTime.Now.ToString();
byte[] timeBytes = Encoding.ASCII.GetBytes(currentTime);
stream.Write(timeBytes, 0, timeBytes.Length);
Console.WriteLine($"已發送時間:{currentTime}");
}
}
catch (Exception ex)
{
Console.WriteLine($"通訊錯誤:{ex.Message}");
}
finally
{
client.Close();
}
}
}
}
}
new TcpClient(host, port) 會同步阻塞直到連線成功或拋出例外(如 SocketException)。實務上建議使用非同步模式 ConnectAsync 避免 UI 凍結。
NetworkStream 繼承自 Stream,支援同步 Read/Write 與非同步 ReadAsync/WriteAsync。讀取時需預先配置緩衝區(byte[]),Read 回傳實際讀取位元組數,這對正確解碼字串至關重要。
善用 using 區塊確保 TcpClient、NetworkStream 等實作 IDisposable 的物件正確釋放,避免連線洩漏導致伺服器資源耗盡。
掌握此基礎後,您可以延伸開發:
.NET 的 TcpClient 與 TcpListener 將複雜的 Socket 程式設計封裝為直觀的物件模型,配合 NetworkStream 的串流抽象,使 TCP 網路程式開發變得前所未有的簡單。本範例展示了同步阻塞模式的基本用法,實際專案中建議結合 async/await 非同步模式與 CancellationToken 打造高併發、可擴展的網路服務。