首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 網路程式設計基礎 (7/7):同步伺服器接受單一用戶端連線

     編輯:關於C語言

AcceptTcpClient:同步阻塞方法

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,確認連線雙向建立。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved