IPAddress (本機回環 127.0.0.1)。TcpListener 指定 IP 與 Port (如 8500)。Start() 開啟監聽。Console.ReadKey) 維持進程存活,否則監聽隨進程結束而停止。using System.Net;
using System.Net.Sockets;
class Server
{
static void Main()
{
Console.WriteLine("Server is running ...");
IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
// 也可用 IPAddress.Parse("127.0.0.1") 或 Dns.GetHostEntry("localhost").AddressList[0]
TcpListener listener = new TcpListener(ip, 8500);
listener.Start();
Console.WriteLine("Start Listening ...");
Console.WriteLine("Press Q to quit...");
while (Console.ReadKey(true).Key != ConsoleKey.Q) { }
}
}
TCP jimmy:1030 0.0.0.0:0 LISTENING
TCP jimmy:3603 0.0.0.0:0 LISTENING
TCP jimmy:8500 0.0.0.0:0 LISTENING ← 我們的 Port
TCP jimmy:netbios-ssn 0.0.0.0:0 LISTENING
狀態 LISTENING 表示監聽成功,等待用戶端連線。