C#的Socket程式(TCP)

來源:互聯網
上載者:User

其實只要用到Socket聯結,基本上就得使用Thread,是交叉使用的。

C#封裝的Socket用法基本上不算很複雜,只是不知道託管之後的Socket有沒有其他效能或者安全上的問題。

在C#裡面能找到的最底層的操作也就是socket了,概念不做解釋。

程式模型如下:

WinForm程式 : 啟動連接埠偵聽;監視Socket聯結情況;定期關閉不活動的聯結;

Listener:處理Socket的Accept函數,偵聽新連結,建立新Thread來處理這些聯結(Connection)。

Connection:處理具體的每一個聯結的會話。

1:WinForm如何啟動一個新的線程來啟動Listener:

//start the server
    private void btn_startServer_Click(object sender, EventArgs e)
    {
      //this.btn_startServer.Enabled = false;
      Thread _createServer = new Thread(new ThreadStart(WaitForConnect));
      _createServer.Start();
    }
    //wait all connections
    private void WaitForConnect()
    {
      SocketListener listener = new SocketListener(Convert.ToInt32(this.txt_port.Text));
       listener.StartListening();
    }

因為偵聽聯結是一個迴圈等待的函數,所以不可能在WinForm的線程裡面直接執行,不然Winform也就是無法繼續任何操作了,所以才指定一個新的線程來執行這個函數,啟動偵聽迴圈。

這一個新的線程是比較簡單的,基本上沒有啟動的參數,直接指定處理函數就可以了。

2:Listener如何啟動迴圈偵聽,並且啟動新的帶有參數的線程來處理Socket聯結會話。

先看如何建立偵聽:(StartListening函數)

IPEndPoint localEndPoint = new IPEndPoint(_ipAddress, _port);
    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      // Bind the socket to the local endpoint and listen for incoming connections.
      try
      {
        listener.Bind(localEndPoint);
        listener.Listen(20);//20 trucks

// Start listening for connections.
        while (true)
        {
          // here will be suspended while waiting for a new connection.
          Socket connection = listener.Accept();
          Logger.Log("Connect", connection.RemoteEndPoint.ToString());//log it, new connection
        ……
      }
     }……

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.