listener.AcceptTcpClient() 會暫停執行緒,直到有用戶端連線,才回傳代表該連線的 TcpClient。類比 Console.ReadLine() 等待輸入。
class Server
{
static void Main()
{
Console.WriteLine("Server is running ...");
IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpListener listener = new TcpListener(ip, 8500);
listener.Start();
Console.WriteLine("Start Listening ...");
TcpClient remoteClient = listener.AcceptTcpClient(); // 阻塞等待
Console.WriteLine("Client Connected! {0} <-- {1}",
remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
Console.WriteLine("Press Q to quit...");
while (Console.ReadKey(true).Key != ConsoleKey.Q) { }
}
}
class Client
{
static void Main()
{
Console.WriteLine("Client Running ...");
TcpClient client = new TcpClient();
try { client.Connect("localhost", 8500); }
catch (Exception ex) { Console.WriteLine(ex.Message); return; }
Console.WriteLine("Server Connected! {0} --> {1}",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
Console.WriteLine("Press Q to quit...");
while (Console.ReadKey(true).Key != ConsoleKey.Q) { }
}
}
// Server
Server is running ...
Start Listening ...
Client Connected! 127.0.0.1:8500 <-- 127.0.0.1:5188
// Client
Client Running ...
Server Connected! 127.0.0.1:5188 --> 127.0.0.1:8500
雙方各自看到對方的 IP:Port,確認連線雙向建立。