我正在尝试使我的Socket“基于事件”。以下是我的尝试:
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
}
我不知道如何继续前进。我该如何检查是否发生了任何所需的事件?我怎样才能不断检查这些事件?这会在一段时间(1)循环吗?
我在互联网上找到的所有例子都是针对多个套接字的。但是,在我的情况下,我只有一个插槽,我想让它为读取和写入“事件驱动”。请帮我。我被卡住了!
答案 0 :(得分: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);