1

我正在尝试使我的套接字“基于事件”。以下是我尝试过的:

VOID createServerSocket()
{
   WSADATA wsa; 

   //Initialise winsock//
   if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
      {

        //"WinSock Initialization FAILED",

      }

   //Create a socket//

  SOCKET newSocketIdentifier;
  SOCKADDR_IN newSocket;

  if((newSocketIdentifier = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
      {                 

        //Socket Creation Failed

      }
   //Socket Created//

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

   //Bind//
   if( bind(newSocketIdentifier ,(struct sockaddr *)&newSocket, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
      { 
       //Bind Failed
      }

   //Bind Done//

   WSAEVENT NewEvent = WSACreateEvent();
   WSAEventSelect(newSocketIdentifier, NewEvent, FD_READ | FD_WRITE); //made the socket "newSocketIdentifier" event based for events "FD_READ" and FD_WRITE

}

我不知道如何进一步进行。我该如何检查是否发生了任何所需的事件?我怎样才能不断地检查这些事件?那会在一些 while(1) 循环下吗?

我在互联网上找到的所有示例都是针对多个套接字的。但是,就我而言,我只有一个套接字,我想让它“事件驱动”以进行读写。请帮我。我被困住了!

4

1 回答 1

1

假设您想侦听传入的 UDP 数据包,请尝试使用以下代码片段并查看。

/ Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
    printf("Error at WSAStartup()\n");

// Create a socket.
SOCKET m_socket[1];
m_socket[0] = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );

if ( m_socket[0] == INVALID_SOCKET ) {
    printf( "Error at socket(): %ld\n", WSAGetLastError() );
    WSACleanup();
    return;
}

// Bind the socket.
sockaddr_in service[1];

service[0].sin_family = AF_INET;
service[0].sin_addr.s_addr = INADDR_ANY;
service[0].sin_port = htons( 8888 );

if ( bind( m_socket[0], (SOCKADDR*) &service[0], sizeof(service[0]) ) == SOCKET_ERROR ) {
    printf( "bind() failed.\n" );
    closesocket(m_socket[0]);
    return;
}

char data[256];
int bytes, waitRet;

WSAEVENT hEvent = WSACreateEvent();
WSANETWORKEVENTS events;
WSAEventSelect(*m_socket, hEvent, FD_READ | FD_WRITE);
while(1)
{
    waitRet = WSAWaitForMultipleEvents(2, &hEvent, FALSE, WSA_INFINITE, FALSE);
    if(WSAEnumNetworkEvents(*m_socket,hEvent,&events) == SOCKET_ERROR)
    {
        cout << "Error";
    }
    else
    {
        if(events.lNetworkEvents & FD_READ)
        {
            bytes = recv(*m_socket, data, 256, 0);
            cout << data << endl;
        }
    }
}

WSACloseEvent(hEvent);
于 2013-05-07T10:09:31.200 回答