资源描述:
《socket c++ tcp阻塞 非阻塞总结》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、0、可运行实例及基本知识1、如何设置socket函数的非阻塞调用?2、深入CSocket编程之阻塞和非阻塞模式3、SOCKET类的设计和实现服务器#include"stdafx.h"#include#include#include#include#include#include#pragmacomment(lib,"ws2_32.lib")#defineSERVPORT7861/*服务器监听端口号*/#defineMAXDATASIZE100#de
2、fineBACKLOG10usingnamespacestd;std::vectorclient_fd;charbuf[MAXDATASIZE];DWORDWINAPIqtPingServerThreadFunc(LPVOIDlpThreadParameter);int_tmain(intargc,_TCHAR*argv[]){SOCKETsockfd;/*sock_fd:监听socket;client_fd:数据传输socket*/structsockaddr_inmy_addr;/*本机地址信息*/structsockaddr_inremote_ad
3、dr;/*客户端地址信息*/charszMsg[]="hello";WORDwVersionRequested;WSADATAwsaData;interr;wVersionRequested=MAKEWORD(2,0);err=WSAStartup(wVersionRequested,&wsaData);if(0!=err){cout<<"Socketfailed";return0;}if(LOBYTE(wsaData.wVersion)!=2
4、
5、HIBYTE(wsaData.wVersion)!=0)otherstaffoftheCentre.Duringthewar
6、,ZhuwastransferredbacktoJiangxi,andDirectorofthenewOfficeinJingdezhen,JiangxiCommitteeSecretary.Startingin1939servedasrecorderoftheWestNorthOrganization,SecretaryoftheSpecialCommitteeAfterthevictoryofthelongMarch,hehasbeentheNorthwestOfficeoftheFederationofStateenterprisesMinister,Shenmu
7、fuguSARmissions,DirectorofNingxiaCountypartyCommitteeSecretaryandrecorderoftheCountypartyCommitteeSecretary,Ministersand{WSACleanup();return0;}sockfd=socket(AF_INET,SOCK_STREAM,0);if(INVALID_SOCKET==sockfd){cout<<"SoketCreateFailed";return0;}/*sockfd=socket(AF_INET,SOCK_STREAM,0);*/if(so
8、ckfd==-1){perror("socket创建出错!");exit(1);}my_addr.sin_family=AF_INET;my_addr.sin_port=htons(SERVPORT);my_addr.sin_addr.s_addr=INADDR_ANY;memset(&(my_addr.sin_zero),0,8);if(bind(sockfd,(structsockaddr*)&my_addr,sizeof(structsockaddr))==-1){perror("bind出错!");//exit(1);}intn=0;while(1){if(li
9、sten(sockfd,BACKLOG)!=-1){intsin_size=sizeof(structsockaddr_in);SOCKETnSocket=accept(sockfd,(structsockaddr*)&remote_addr,&sin_size);std::vector::iteratoritr_end=client_fd.end();std::vector::iteratoritr=std::find(client_fd.begin(),itr_end,nSocket);if(itr==