0

我一直在研究非阻塞 udp 套接字。每当有任何数据要通过套接字读取时,我开发的代码都会生成一个窗口消息。下面是代码片段:

void createSocket(HWND hwnd)
{
   ///Socket Binding///
   WSADATA wsa; 
   ///Initialise winsock///
   if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
      {
         exit(EXIT_FAILURE);
      }

   ///Create a socket///
   if((socketIdentifier = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
      {                 
         //Socket Creation Failed
      }
   ///Socket Created///

   ///Prepare the sockaddr_in structure///
   serverSocket.sin_family = AF_INET;
   serverSocket.sin_addr.s_addr = INADDR_ANY;
   serverSocket.sin_port = htons( PORT );

   ///Bind///
   if( bind(socketIdentifier ,(struct sockaddr *)&serverSocket , sizeof(serverSocket)) == SOCKET_ERROR)
      {     
         //Bind Failed      
      }

    WSAAsyncSelect (socketIdentifier, hwnd, MY_MESSAGE_NOTIFICATION, FD_READ | FD_CONNECT | FD_CLOSE | FD_ACCEPT); //Set
   ///Bind Done///

}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);    
int WINAPI WinMain(  HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd 
{
   //Window Created
   createSocket() //Socket Created
   while(GetMessage(&Msg, NULL, 0, 0) > 0)  //Check on Window Messages
      {         
         TranslateMessage(&Msg);
         DispatchMessage(&Msg);
      }
   return Msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
   switch(msg)
   {
    case MY_MESSAGE_NOTIFICATION: //Is a message being sent?
        {
      switch (lParam) //If so, which one is it?
            {
            case FD_ACCEPT:
                //Connection request was made
                break;

            case FD_CONNECT:
                //Connection was made successfully
                break;

            case FD_READ:
               receiveAtSocket();
            break;

            case FD_CLOSE:
                //Lost the connection
             break;
            }
        }
        break;
   }
}

这段代码运行良好,并且套接字不必等待调用 snedto() 或 recvfrom()。相反,只要数据准备好在套接字上读取或写入,就会生成窗口消息。

现在,我想找到一些其他方式来通知数据数据已准备好,而不是窗口消息。即,只要有数据要在套接字上读取或写入,我不希望生成任何窗口消息。

有没有其他方法可以在不使用窗口消息的情况下实现上述功能>请帮助我。

等待帮助:(

4

1 回答 1

1

另一种方法是使用 WaitForSingleObject 或 WaitForMultipleObjects 或它们的兄弟。你可以在这里看到一些代码:Asynchronous winsock server wrapper, CPU lagging - C++

于 2013-05-04T08:30:52.553 回答