资源描述:
《Windows Socket IO模型》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、WindowsSocketI/O模型---重叠I/O模型、完成端口模型四.重叠I/O模型Winsock2的发布使得SocketI/O有了和文件I/O统一的接口。我们可以通过使用Win32文件操纵函数ReadFile和WriteFile来进行SocketI/O。伴随而来的,用于普通文件I/O的重叠I/O模型和完成端口模型对SocketI/O也适用了。这些模型的优点是可以达到更佳的系统性能,但是实现较为复杂,里面涉及较多的C语言技巧。例如我们在完成端口模型中会经常用到所谓的“尾随数据”。1.用事件通知方
2、式实现的重叠I/O模型#include#include#definePORT 5150#defineMSGSIZE1024#pragmacomment(lib,"ws2_32.lib")typedefstruct{ WSAOVERLAPPEDoverlap; WSABUF Buffer; char szMessage[MSGSIZE]; DWORD NumberOfBytesRecvd; DWO
3、RD Flags;}PER_IO_OPERATION_DATA,*LPPER_IO_OPERATION_DATA;int g_iTotalConn=0;SOCKET g_CliSocketArr[MAXIMUM_WAIT_OBJECTS];WSAEVENT g_CliEventArr[MAXIMUM_WAIT_OBJECTS];LPPER_IO_OPERATION_DATAg_pP
4、erIODataArr[MAXIMUM_WAIT_OBJECTS];DWORDWINAPIWorkerThread(LPVOID);voidCleanup(int);intmain(){ WSADATA wsaData; SOCKET sListen,sClient; SOCKADDR_INlocal,client; DWORD dwThreadId; int iaddrSize=sizeof(SOCKADDR_IN); //Initiali
5、zeWindowsSocketlibrary WSAStartup(0x0202,&wsaData); //Createlisteningsocket sListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); //Bind local.sin_addr.S_un.S_addr=htonl(INADDR_ANY); local.sin_family=AF_INET; local.sin_port=htons(PORT); bind(sListen
6、,(structsockaddr*)&local,sizeof(SOCKADDR_IN)); //Listen listen(sListen,3); //Createworkerthread CreateThread(NULL,0,WorkerThread,NULL,0,&dwThreadId); while(TRUE) { //Acceptaconnection sClient=accept(sListen,(structsockaddr*)&client,&iaddrSi
7、ze); printf("Acceptedclient:%s:%d",inet_ntoa(client.sin_addr),ntohs(client.sin_port)); g_CliSocketArr[g_iTotalConn]=sClient; //AllocateaPER_IO_OPERATION_DATAstructure g_pPerIODataArr[g_iTotalConn]=(LPPER_IO_OPERATION_DATA)HeapAlloc(
8、 GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PER_IO_OPERATION_DATA)); g_pPerIODataArr[g_iTotalConn]->Buffer.len=MSGSIZE; g_pPerIODataArr[g_iTotalConn]->Buffer.buf=g_pPerIODataArr[g_iTotalConn]->szMessage; g_CliEventA