TcpClient類的使用,摘自MSDN-c#

來源:互聯網
上載者:User

TcpClient 為 TCP 網路服務提供用戶端串連。

System.Object
   System.Net.Sockets.TcpClient

[C#]public class TcpClient : IDisposable

備忘

TcpClient 類提供了一些簡單的方法,用於在同步阻塞模式下通過網路來串連、發送和接收流資料。

為使 TcpClient 串連並交換資料,使用 TCP ProtocolType 建立的 TcpListenerSocket 必須偵聽是否有傳入的串連請求。可以使用下面兩種方法之一串連到該接聽程式:

  • 建立一個 TcpClient,並調用三個可用的 Connect 方法之一。
  • 使用遠程主機的主機名稱和連接埠號碼建立 TcpClient。此建構函式將自動嘗試一個串連。

注意   如果要在同步阻塞模式下發送無串連資料報,請使用 UdpClient 類。

對繼承者的說明:  要發送和接收資料,請使用 GetStream 方法來擷取一個 NetworkStream。調用 NetworkStreamWriteRead 方法與遠程主機之間發送和接收資料。使用 Close 方法釋放與 TcpClient 關聯的所有資源。

樣本  C#下面的樣本建立 TcpClient 串連。 
static void Connect(String server, String message)
{
  try
  {
    // Create a TcpClient.
    // Note, for this client to work you need to have a TcpServer
    // connected to the same address as specified by the server, port
    // combination.
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);
   
    // Translate the passed message into ASCII and store it as a Byte array.
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);        

    // Get a client stream for reading and writing.
   //  Stream stream = client.GetStream();
   
    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer.
    stream.Write(data, 0, data.Length);

    Console.WriteLine("Sent: {0}", message);        

    // Receive the TcpServer.response.
   
    // Buffer to store the response bytes.
    data = new Byte[256];

    // String to store the response ASCII representation.
    String responseData = String.Empty;

    // Read the first batch of the TcpServer response bytes.
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    Console.WriteLine("Received: {0}", responseData);        

    // Close everything.
    client.Close();        
  }
  catch (ArgumentNullException e)
  {
    Console.WriteLine("ArgumentNullException: {0}", e);
  }
  catch (SocketException e)
  {
    Console.WriteLine("SocketException: {0}", e);
  }
   
  Console.WriteLine("\n Press Enter to continue...");
  Console.Read();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.