// 实验九基于事件模型的网络通信.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<conio.h>
#include<ws2tcpip.h>
#include<stdio.h>
#include <time.h>
#include<winsock2.h>
int main(int argc, char* argv[])
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
printf("初始化不成功 error %d\n", iResult);
return 1;
}
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
struct sockaddr_in hints;
hints.sin_family = AF_INET;
hints.sin_port = htons(2000);
hints.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
if (s == INVALID_SOCKET)
{
printf("初始化不成功 error \n");
WSACleanup();
}
int result = bind(s, (struct sockaddr *)&hints, sizeof(hints));
if (result == -1)
{
printf("Failed to bind socket\n");
WSACleanup();
return 1;
}
listen(s, 105);
WSAEVENT Event =WSACreateEvent();
int iIndex=0;
int iEventTotal=0;
WSAEVENT eventArray[50];
WSAEVENT sockArray[50];
WSAEventSelect(s,Event,FD_ACCEPT);
eventArray[iEventTotal]=Event;
sockArray[iEventTotal] = (WSAEVENT)s;
iEventTotal++;
struct sockaddr_in addrClient;
int addrClientlen = sizeof(addrClient);
char buf[100];
memset((void *)buf, 0, 100);
while(1){
iIndex=WSAWaitForMultipleEvents(50,eventArray,0,WSA_INFINITE,0);
iIndex=iIndex-WSA_WAIT_EVENT_0;
for(int i=iIndex;i<iEventTotal;i++){
iResult=WSAWaitForMultipleEvents(1,&eventArray[i],1,1000,0);
if(iResult==WSA_WAIT_FAILED||iResult==WSA_WAIT_TIMEOUT){continue;}
else {
// WSANETWORKEVENTS newevent; // 声明newevent为WSANETWORKEVENTS结构
// WSAEnumNetworkEvents(sockArray[i], eventArray[i], &newevent); // 传递newevent的地址
}
}
}
}