static void Main() {
int port = 2000; string host = "127.0.0.1";
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(host), port);
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Connecting...");
c.Connect(ipe); // 連線至伺服器
string msg = "hello! This is a socket test";
byte[] data = Encoding.ASCII.GetBytes(msg);
c.Send(data); // 發送
byte[] buffer = new byte[1024];
int len = c.Receive(buffer); // 接收回應
string reply = Encoding.ASCII.GetString(buffer, 0, len);
Console.WriteLine("Client Get Message: " + reply);
c.Close();
}
IPEndPoint:IP + Port 端點封裝Socket 建構:InterNetwork(IPv4)、Stream(串流)、TcpConnect:主動發起三向交握Send/Receive:同步阻塞收發,需自行處理封包邊界(本例簡化假設單次收發完整)ArgumentNullException、SocketException下一篇將實作伺服器端對應程式碼。