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同時提供了充當服務器和客戶端的功能.當然在這個基礎上你可以很方便的做出你想要的效果.