程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 異步Socket(3)

異步Socket(3)

編輯:關於C語言

BeginConnect為連接成功設置了回調方法OnConnect, 一旦與服務器連接成功就會執行該方法.來看看OnConnect具體做了什麼

    /**//// <summary>
    /// Callback used when a server accept a connection.
    /// setup to receive message
    /// </summary>
    /// <param name="ar"></param>
    public void OnConnect(IAsyncResult ar)
    {
      // Socket was the passed in object
      Socket sock = (Socket)ar.AsyncState;
      // Check if we were sucessfull
      try
      {
        //sock.EndConnect( ar );
        if (sock.Connected)
        {
          AsyncCallback recieveData = new AsyncCallback(OnRecIEvedData);
          sock.BeginReceive(msgBuff, 0, msgBuff.Length, SocketFlags.None, recIEveData, sock);
        }        
else
          Console.WriteLine("Unable to connect to remote Machine", "Connect Failed!");
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message, "Unusual error during Connect!");
      }
    }

它在檢測確實連接成功後, 又使用BeginReceive注冊了接受數據的回調函數.

/**//// <summary>
    /// Callback used when receive data., both for server or clIEnt
    /// Note: If not data was recieved the connection has probably dIEd.
    /// </summary>
    /// <param name="ar"></param>
    public void OnRecIEvedData(IAsyncResult ar)
    {
      Socket sock = (Socket)ar.AsyncState;
      // Check if we got any data
      try
      {
        int nBytesRec = sock.EndReceive(ar);
        if (nBytesRec > 0)
        {
          // Wrote the data to the List
          string sRecIEved = Encoding.ASCII.GetString(msgBuff, 0, nBytesRec);
          ParseMessage(sock ,sRecIEved);
          // If the connection is still usable restablish the callback
          SetupRecIEveCallback(sock);
        }
        else
        {
          // If no data was recIEved then the connection is probably dead
          Console.WriteLine("disconnect from server {0}", sock.RemoteEndPoint);
          sock.Shutdown(SocketShutdown.Both);
          sock.Close();
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message, "Unusual error druing RecIEve!");
      }
    }

它在檢測確實連接成功後又使用注冊了接受數據的回調函數

我們可以發現在整個過程中就是通過事件的不斷觸發, 然後在預先設置好的回調函數中做相應的處理工作,比如發送接受數據.下面這幅圖將讓你對這個事件觸發的過程有一個形象的認識.

配合附帶的源代碼, 相信可以讓你對此過程有更加深入的了解.

至於本文有關P2P的示例, 其實還很不完善.只是為每個Peer同時提供了充當服務器和客戶端的功能.當然在這個基礎上你可以很方便的做出你想要的效果.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved