1、SocketAsyncEventArgs介紹
SocketAsyncEventArgs是微軟提供的高性能異步Socket實現(xiàn)類,,主要為高性能網(wǎng)絡服務器應用程序而設計,主要是為了避免在在異步套接字 I/O 量非常大時發(fā)生重復的對象分配和同步,。使用此類執(zhí)行異步套接字操作的模式包含以下步驟:
1.分配一個新的 SocketAsyncEventArgs 上下文對象,或者從應用程序池中獲取一個空閑的此類對象,。
2.將該上下文對象的屬性設置為要執(zhí)行的操作(例如,完成回調方法,、數(shù)據(jù)緩沖區(qū),、緩沖區(qū)偏移量以及要傳輸?shù)淖畲髷?shù)據(jù)量)。
3.調用適當?shù)奶捉幼址椒?(xxxAsync) 以啟動異步操作,。
4.如果異步套接字方法 (xxxAsync) 返回 true,,則在回調中查詢上下文屬性來獲取完成狀態(tài)。
5.如果異步套接字方法 (xxxAsync) 返回 false,,則說明操作是同步完成的,。 可以查詢上下文屬性來獲取操作結果,。
6.將該上下文重用于另一個操作,將它放回到應用程序池中,,或者將它丟棄,。
2、SocketAsyncEventArgs封裝
使用SocketAsyncEventArgs之前需要先建立一個Socket監(jiān)聽對象,,使用如下代碼:
- public void Start(IPEndPoint localEndPoint)
- {
- listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- listenSocket.Bind(localEndPoint);
- listenSocket.Listen(m_numConnections);
- Program.Logger.InfoFormat("Start listen socket {0} success", localEndPoint.ToString());
- //for (int i = 0; i < 64; i++) //不能循環(huán)投遞多次AcceptAsync,,會造成只接收8000連接后不接收連接了
- StartAccept(null);
- m_daemonThread = new DaemonThread(this);
- }
然后開始接受連接,SocketAsyncEventArgs有連接時會通過Completed事件通知外面,,所以接受連接的代碼如下:
- public void StartAccept(SocketAsyncEventArgs acceptEventArgs)
- {
- if (acceptEventArgs == null)
- {
- acceptEventArgs = new SocketAsyncEventArgs();
- acceptEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
- }
- else
- {
- acceptEventArgs.AcceptSocket = null; //釋放上次綁定的Socket,,等待下一個Socket連接
- }
-
- m_maxNumberAcceptedClients.WaitOne(); //獲取信號量
- bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArgs);
- if (!willRaiseEvent)
- {
- ProcessAccept(acceptEventArgs);
- }
- }
接受連接響應事件代碼:
- void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs acceptEventArgs)
- {
- try
- {
- ProcessAccept(acceptEventArgs);
- }
- catch (Exception E)
- {
- Program.Logger.ErrorFormat("Accept client {0} error, message: {1}", acceptEventArgs.AcceptSocket, E.Message);
- Program.Logger.Error(E.StackTrace);
- }
- }
- private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
- {
- Program.Logger.InfoFormat("Client connection accepted. Local Address: {0}, Remote Address: {1}",
- acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);
-
- AsyncSocketUserToken userToken = m_asyncSocketUserTokenPool.Pop();
- m_asyncSocketUserTokenList.Add(userToken); //添加到正在連接列表
- userToken.ConnectSocket = acceptEventArgs.AcceptSocket;
- userToken.ConnectDateTime = DateTime.Now;
-
- try
- {
- bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投遞接收請求
- if (!willRaiseEvent)
- {
- lock (userToken)
- {
- ProcessReceive(userToken.ReceiveEventArgs);
- }
- }
- }
- catch (Exception E)
- {
- Program.Logger.ErrorFormat("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
- Program.Logger.Error(E.StackTrace);
- }
-
- StartAccept(acceptEventArgs); //把當前異步事件釋放,等待下次連接
- }
接受連接后,,從當前Socket緩沖池AsyncSocketUserTokenPool中獲取一個用戶對象AsyncSocketUserToken,,AsyncSocketUserToken包含一個接收異步事件m_receiveEventArgs,一個發(fā)送異步事件m_sendEventArgs,,接收數(shù)據(jù)緩沖區(qū)m_receiveBuffer,,發(fā)送數(shù)據(jù)緩沖區(qū)m_sendBuffer,協(xié)議邏輯調用對象m_asyncSocketInvokeElement,,建立服務對象后,,需要實現(xiàn)接收和發(fā)送的事件響應函數(shù):
- void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs)
- {
- AsyncSocketUserToken userToken = asyncEventArgs.UserToken as AsyncSocketUserToken;
- userToken.ActiveDateTime = DateTime.Now;
- try
- {
- lock (userToken)
- {
- if (asyncEventArgs.LastOperation == SocketAsyncOperation.Receive)
- ProcessReceive(asyncEventArgs);
- else if (asyncEventArgs.LastOperation == SocketAsyncOperation.Send)
- ProcessSend(asyncEventArgs);
- else
- throw new ArgumentException("The last operation completed on the socket was not a receive or send");
- }
- }
- catch (Exception E)
- {
- Program.Logger.ErrorFormat("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, E.Message);
- Program.Logger.Error(E.StackTrace);
- }
- }
在Completed事件中需要處理發(fā)送和接收的具體邏輯代碼,其中接收的邏輯實現(xiàn)如下:
- private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs)
- {
- AsyncSocketUserToken userToken = receiveEventArgs.UserToken as AsyncSocketUserToken;
- if (userToken.ConnectSocket == null)
- return;
- userToken.ActiveDateTime = DateTime.Now;
- if (userToken.ReceiveEventArgs.BytesTransferred > 0 && userToken.ReceiveEventArgs.SocketError == SocketError.Success)
- {
- int offset = userToken.ReceiveEventArgs.Offset;
- int count = userToken.ReceiveEventArgs.BytesTransferred;
- if ((userToken.AsyncSocketInvokeElement == null) & (userToken.ConnectSocket != null)) //存在Socket對象,,并且沒有綁定協(xié)議對象,,則進行協(xié)議對象綁定
- {
- BuildingSocketInvokeElement(userToken);
- offset = offset + 1;
- count = count - 1;
- }
- if (userToken.AsyncSocketInvokeElement == null) //如果沒有解析對象,提示非法連接并關閉連接
- {
- Program.Logger.WarnFormat("Illegal client connection. Local Address: {0}, Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
- userToken.ConnectSocket.RemoteEndPoint);
- CloseClientSocket(userToken);
- }
- else
- {
- if (count > 0) //處理接收數(shù)據(jù)
- {
- if (!userToken.AsyncSocketInvokeElement.ProcessReceive(userToken.ReceiveEventArgs.Buffer, offset, count))
- { //如果處理數(shù)據(jù)返回失敗,,則斷開連接
- CloseClientSocket(userToken);
- }
- else //否則投遞下次介紹數(shù)據(jù)請求
- {
- bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投遞接收請求
- if (!willRaiseEvent)
- ProcessReceive(userToken.ReceiveEventArgs);
- }
- }
- else
- {
- bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投遞接收請求
- if (!willRaiseEvent)
- ProcessReceive(userToken.ReceiveEventArgs);
- }
- }
- }
- else
- {
- CloseClientSocket(userToken);
- }
- }
由于我們制定的協(xié)議第一個字節(jié)是協(xié)議標識,因此在接收到第一個字節(jié)的時候需要綁定協(xié)議解析對象,,具體代碼實現(xiàn)如下:
- private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken)
- {
- byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset];
- if (flag == (byte)SocketFlag.Upload)
- userToken.AsyncSocketInvokeElement = new UploadSocketProtocol(this, userToken);
- else if (flag == (byte)SocketFlag.Download)
- userToken.AsyncSocketInvokeElement = new DownloadSocketProtocol(this, userToken);
- else if (flag == (byte)SocketFlag.RemoteStream)
- userToken.AsyncSocketInvokeElement = new RemoteStreamSocketProtocol(this, userToken);
- else if (flag == (byte)SocketFlag.Throughput)
- userToken.AsyncSocketInvokeElement = new ThroughputSocketProtocol(this, userToken);
- else if (flag == (byte)SocketFlag.Control)
- userToken.AsyncSocketInvokeElement = new ControlSocketProtocol(this, userToken);
- else if (flag == (byte)SocketFlag.LogOutput)
- userToken.AsyncSocketInvokeElement = new LogOutputSocketProtocol(this, userToken);
- if (userToken.AsyncSocketInvokeElement != null)
- {
- Program.Logger.InfoFormat("Building socket invoke element {0}.Local Address: {1}, Remote Address: {2}",
- userToken.AsyncSocketInvokeElement, userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint);
- }
- }
發(fā)送響應函數(shù)實現(xiàn)需要注意,,我們是把發(fā)送數(shù)據(jù)放到一個列表中,當上一個發(fā)送事件完成響應Completed事件,,這時我們需要檢測發(fā)送隊列中是否存在未發(fā)送的數(shù)據(jù),如果存在則繼續(xù)發(fā)送,。
- private bool ProcessSend(SocketAsyncEventArgs sendEventArgs)
- {
- AsyncSocketUserToken userToken = sendEventArgs.UserToken as AsyncSocketUserToken;
- if (userToken.AsyncSocketInvokeElement == null)
- return false;
- userToken.ActiveDateTime = DateTime.Now;
- if (sendEventArgs.SocketError == SocketError.Success)
- return userToken.AsyncSocketInvokeElement.SendCompleted(); //調用子類回調函數(shù)
- else
- {
- CloseClientSocket(userToken);
- return false;
- }
- }
SendCompleted用于回調下次需要發(fā)送的數(shù)據(jù),具體實現(xiàn)過程如下:
- public virtual bool SendCompleted()
- {
- m_activeDT = DateTime.UtcNow;
- m_sendAsync = false;
- AsyncSendBufferManager asyncSendBufferManager = m_asyncSocketUserToken.SendBuffer;
- asyncSendBufferManager.ClearFirstPacket(); //清除已發(fā)送的包
- int offset = 0;
- int count = 0;
- if (asyncSendBufferManager.GetFirstPacket(ref offset, ref count))
- {
- m_sendAsync = true;
- return m_asyncSocketServer.SendAsyncEvent(m_asyncSocketUserToken.ConnectSocket, m_asyncSocketUserToken.SendEventArgs,
- asyncSendBufferManager.DynamicBufferManager.Buffer, offset, count);
- }
- else
- return SendCallback();
- }
-
- //發(fā)送回調函數(shù),,用于連續(xù)下發(fā)數(shù)據(jù)
- public virtual bool SendCallback()
- {
- return true;
- }
當一個SocketAsyncEventArgs斷開后,我們需要斷開對應的Socket連接,,并釋放對應資源,,具體實現(xiàn)函數(shù)如下:
- public void CloseClientSocket(AsyncSocketUserToken userToken)
- {
- if (userToken.ConnectSocket == null)
- return;
- string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
- userToken.ConnectSocket.RemoteEndPoint);
- Program.Logger.InfoFormat("Client connection disconnected. {0}", socketInfo);
- try
- {
- userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
- }
- catch (Exception E)
- {
- Program.Logger.ErrorFormat("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message);
- }
- userToken.ConnectSocket.Close();
- userToken.ConnectSocket = null; //釋放引用,并清理緩存,,包括釋放協(xié)議對象等資源
-
- m_maxNumberAcceptedClients.Release();
- m_asyncSocketUserTokenPool.Push(userToken);
- m_asyncSocketUserTokenList.Remove(userToken);
- }
3、SocketAsyncEventArgs封裝和MSDN的不同點
MSDN在http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socketasynceventargs(v=vs.110).aspx實現(xiàn)了示例代碼,,并實現(xiàn)了初步的池化處理,,我們是在它的基礎上擴展實現(xiàn)了接收數(shù)據(jù)緩沖,發(fā)送數(shù)據(jù)隊列,,并把發(fā)送SocketAsyncEventArgs和接收SocketAsyncEventArgs分開,,并實現(xiàn)了協(xié)議解析單元,這樣做的好處是方便后續(xù)邏輯實現(xiàn)文件的上傳,,下載和日志輸出,。
|