资源描述:
《C++_Socket网络编程大全.pdf》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1.简单服务器/*#include#pragmacomment(lib,"WS2_32.lib")*/WSADATAwsd;staticUINTport=%%1;UINTListen(LPVOIDpParam){SOCKETsServer,sClient;charbuf[1024];intretVal;if(WSAStartup(MAKEWORD(2,2),&wsd)!=0){return-1;//失败}sServer=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(I
2、NVALID_SOCKET==sServer){WSACleanup();return-1;//创建套接字失败}SOCKADDR_INaddrServ;addrServ.sin_family=AF_INET;addrServ.sin_port=htons((short)pParam);addrServ.sin_addr.s_addr=INADDR_ANY;retVal=bind(sServer,(LPSOCKADDR)&addrServ,sizeof(SOCKADDR_IN));if(SOCKET_ERROR==retVal){c
3、losesocket(sServer);WSACleanup();return-1;//绑定套接字失败}retVal=listen(sServer,1);if(SOCKET_ERROR==retVal){closesocket(sServer);WSACleanup();return-1;//开始监听失败}sockaddr_inaddrClient;intaddrClientlen=sizeof(addrClient);sClient=accept(sServer,(sockaddrFAR*)&addrClient,&addrCl
4、ientlen);if(INVALID_SOCKET==sClient){closesocket(sServer);WSACleanup();return-1;//开始接受客户端连接失败}ZeroMemory(buf,sizeof(buf));retVal=recv(sClient,buf,sizeof(buf),0);if(SOCKET_ERROR==retVal){closesocket(sServer);closesocket(sClient);WSACleanup();file:///C
5、/DocumentsandSett
6、ings/ITboy/桌面/新建文件夹(2)/C++_Socket网络编程大全.txt[2010-4-230:29:18]return-1;//接收数据失败}CString%%2(buf);closesocket(sServer);closesocket(sClient);WSACleanup();return0;}CWinThread*pThread=AfxBeginThread(Listen,&port);2.简单客户端/*#include#pragmacomment(lib,"WS2_32.lib")
7、*/WSADATAwsd;SOCKETsHost;SOCKADDR_INservAddr;charbuf[1024];intretVal;if(WSAStartup(MAKEWORD(2,2),&wsd)!=0){return-1;//失败}sHost=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if(INVALID_SOCKET==sHost){WSACleanup();return-1;//创建套接字失败}servAddr.sin_family=AF_INET;servAddr.sin_ad
8、dr.s_addr=inet_addr(%%3);servAddr.sin_port=htons((short)%%2);intnServAddlen=sizeof(servAddr);retVal=connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr));if(SOCKET_ERROR==retVal){closesocket(sHost);WSACleanup();return-1;//连接服务器失败}ZeroMemory(buf,sizeof(buf));strcpy(buf
9、,%%3);retVal=send(sHost,buf,sizeof(buf),0);if(SOCKET_ERROR==retVal){closesocket(sHost);WSACleanup();return-1;//向服务器发送数据失败}cl