bool CAsyncSocket::Create(
long lEvent ) file:
//參數lEvent是指定你所關心的Socket事件
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
m_hSocket = socket( PF_INET, SOCK_STREAM, 0 ); file:
//建立Socket自己
![](http://static.javashuo.com/static/loading.gif)
CSocketWnd* pSockWnd =
new CSocketWnd; file:
//建立響應事件的窗口,實際的這個窗口在AfxSockInit()調用時就被建立了。
![](http://static.javashuo.com/static/loading.gif)
pSockWnd->Create(...);
![](http://static.javashuo.com/static/loading.gif)
WSAAsyncSelect( m_hSocket, pSockWnd->m_hWnd, WM_SOCKET_NOTIFY, lEvent ); file:
//Socket事件和窗口關聯
![](http://static.javashuo.com/static/loading.gif)
}
static
void PASCAL CAsyncSocket::DoCallBack(WPARAM wParam, LPARAM lParam)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
CAsyncSocket Socket;
![](http://static.javashuo.com/static/loading.gif)
Socket.Attach( (SOCKET)wParam ); file:
//wParam就是觸發這個事件的Socket的句柄
int nErrorCode = WSAGETSELECTERROR(lParam); file:
//lParam是錯誤碼與事件碼的合成
switch (WSAGETSELECTEVENT(lParam))
![](http://static.javashuo.com/static/loading.gif)
{
case FD_READ:
![](http://static.javashuo.com/static/loading.gif)
pSocket->OnReceive(nErrorCode);
break;
case FD_WRITE:
![](http://static.javashuo.com/static/loading.gif)
pSocket->OnSend(nErrorCode);
break;
case FD_OOB:
![](http://static.javashuo.com/static/loading.gif)
pSocket->OnOutOfBandData(nErrorCode);
break;
case FD_ACCEPT:
![](http://static.javashuo.com/static/loading.gif)
pSocket->OnAccept(nErrorCode);
break;
case FD_CONNECT:
![](http://static.javashuo.com/static/loading.gif)
pSocket->OnConnect(nErrorCode);
break;
case FD_CLOSE:
![](http://static.javashuo.com/static/loading.gif)
pSocket->OnClose(nErrorCode);
break;
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
CSocketWnd類大體爲:
![](http://static.javashuo.com/static/loading.gif)
BEGIN_MESSAGE_MAP(CSocketWnd, CWnd)
![](http://static.javashuo.com/static/loading.gif)
ON_MESSAGE(WM_SOCKET_NOTIFY, OnSocketNotify)
![](http://static.javashuo.com/static/loading.gif)
END_MESSAGE_MAP()
![](http://static.javashuo.com/static/loading.gif)
LRESULT CSocketWnd::OnSocketNotify(WPARAM wParam, LPARAM lParam)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
CAsyncSocket::DoCallBack( wParam, lParam ); file:
//收到Socket事件消息,回調CAsyncSocket的DoCallBack()函數
return 0L;
![](http://static.javashuo.com/static/loading.gif)
}