在完成端口中使用GetAcceptExSockaddrs

MSDN:When using AcceptEx, the GetAcceptExSockaddrs function must be called to parse the buffer into its three distinct parts (data, local socket address, and remote socket address). On Windows XP and later, once the AcceptEx function completes and the SO_UPDATE_ACCEPT_CONTEXT option is set on the accepted socket, the local address associated with the accepted socket can also be retrieved using the getsockname function. Likewise, the remote address associated with the accepted socket can be retrieved using the getpeername function.

和accept不一樣的是,AcceptEx是非阻塞的,而且在接受客戶端請求前,可以發起n個AcceptEx,當連接建立時(三次握手結束時刻),會有一個接受完成包加入IOCP的完成隊列,按照MSDN上說,就可以在工作線程中,通過調用GetAcceptExSockaddrs解析(parse)1)客戶端發送的第一塊數據,2)本地(Server)套接字地址,3)遠程(Client)套接字地址

工作線程:

      // 取得客戶地址
      int nLocalLen, nRmoteLen;
      LPSOCKADDR pLocalAddr, pRemoteAddr;
      m_lpfnGetAcceptExSockaddrs(
       pBuffer->buff,
       pBuffer->nLen - ((sizeof(sockaddr_in) + 16) * 2),
       sizeof(sockaddr_in) + 16,
       sizeof(sockaddr_in) + 16,
       (SOCKADDR **)&pLocalAddr,
       &nLocalLen,
       (SOCKADDR **)&pRemoteAddr,
       &nRmoteLen);

正如上面說當AcceptEx完成時,並且SO_UPDATE_ACCEPT_CONTEXT選項被設置時,也可以通過getsockname返回local address ,通過調用getpeername返回remote address

設置SO_UPDATE_ACCEPT_CONTEXT原因是:

When the AcceptEx function returns, the socket sAcceptSocket is in the default state for a connected socket. The socket sAcceptSocket does not inherit the properties of the socket associated with sListenSocket parameter until SO_UPDATE_ACCEPT_CONTEXT is set on the socket.

設置:

Use the setsockopt function to set the SO_UPDATE_ACCEPT_CONTEXT option, specifying sAcceptSocket as the socket handle and sListenSocket as the option value.

For example:

 

err = setsockopt( sAcceptSocket, 
    SOL_SOCKET, 
    SO_UPDATE_ACCEPT_CONTEXT, 
    (char *)&sListenSocket, 
    sizeof(sListenSocket) );

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章