使用.NET訪問Internet(4) Paul

來源:互聯網
上載者:User
開始從用戶端通訊端接收資料的 acceptCallback 方法的此節首先初始化 StateObject 類的一個執行個體,然後調用 BeginReceive 方法以開始從用戶端通訊端非同步讀取資料。

下面的樣本顯示了完整的 acceptCallback 方法。它假定以下內容:存在一個名為 allDone 的 ManualResetEvent 執行個體,定義了 StateObject 類,以及在名為 SocketListener 的類中定義了 readCallback 方法。

[C#]
  public static void acceptCallback(IAsyncResult ar) {
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    Socket handler = listener.EndAccept(ar);

    // Signal the main thread to continue.
    allDone.Set();

    // Create the state object.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
      new AsyncCallback(AsynchronousSocketListener.readCallback), state);
  }
需要為非同步通訊端伺服器實現的 final 方法是返回用戶端發送的資料的讀取回調方法。與接受回調方法一樣,讀取回調方法也是一個 AsyncCallback 委託。該方法將來自用戶端通訊端的一個或多個位元組讀入資料緩衝區,然後再次調用 BeginReceive 方法,直到用戶端發送的資料完成為止。從用戶端讀取整個訊息後,在控制台上顯示字串,並關閉處理與用戶端的已連線的服務器通訊端。

下面的樣本實現 readCallback 方法。它假定定義了 StateObject 類。

[C#]
public void readCallback(IAsyncResult ar) {
  StateObject state = (StateObject) ar.AsyncState;
  Socket handler = state.WorkSocket;

  // Read data from the client socket.
  int read = handler.EndReceive(ar);

  // Data was read from the client socket.
  if (read > 0) {
    state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,read));
    handler.BeginReceive(state.buffer,0,StateObject.BufferSize, 0,
      new AsyncCallback(readCallback), state);
  } else {
    if (state.sb.Length > 1) {
      // All the data has been read from the client;
      // display it on the console.
      string content = state.sb.ToString();
      Console.WriteLine("Read {0} bytes from socket.\n Data : {1}",
        content.Length, content);
    }
    handler.Close();
  }
}
同步用戶端通訊端樣本
下面的樣本程式建立一個串連到伺服器的用戶端。該用戶端是用同步通訊端產生的,因此掛起用戶端應用程式的執行,直到伺服器返迴響應為止。該應用程式將字串發送到伺服器,然後在控制台顯示該伺服器返回的字串。

[C#]
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient {

  public static void StartClient() {
    // Data buffer for incoming data.
    byte[] bytes = new byte[1024];

    // Connect to a remote device.
    try {
      // Establish the remote endpoint for the socket.
      //    The name of the
      //   remote device is "host.contoso.com".
      IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
      IPAddress ipAddress = ipHostInfo.AddressList[0];
      IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);

      // Create a TCP/IP  socket.
      Socket sender = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

      // Connect the socket to the remote endpoint. Catch any errors.
      try {
        sender.Connect(remoteEP);

        Console.WriteLine("Socket connected to {0}",
          sender.RemoteEndPoint.ToString());

        // Encode the data string into a byte array.
        byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

        // Send the data through the  socket.
        int bytesSent = sender.Send(msg);

        // Receive the response from the remote device.
        int bytesRec = sender.Receive(bytes);
        Console.WriteLine("Echoed test = {0}",
          Encoding.ASCII.GetString(bytes,0,bytesRec));

        // Release the socket.
        sender.Shutdown(SocketShutdown.Both);
        sender.Close();
        
      } catch (ArgumentNullException ane) {
        Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
      } catch (SocketException se) {
        Console.WriteLine("SocketException : {0}",se.ToString());
      } catch (Exception e) {
        Console.WriteLine("Unexpected exception : {0}", e.ToString());
      }

    } catch (Exception e) {
      Console.WriteLine( e.ToString());
    }
  }
  
  public static int Main(String[] args) {
    StartClient();
    return 0;
  }<





聯繫我們

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