资源描述:
《c++ socket网络编程大全》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、C++Socket网络编程大全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
2、,IPPROTO_TCP);if(INVALID_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(SO
3、CKET_ERROR==retVal){closesocket(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,(sockaddr
4、FAR*)&addrClient,&addrClientlen);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();
5、return-1;//接收数据失败}CString%%2(buf);closesocket(sServer);closesocket(sClient);WSACleanup();return0;}CWinThread*pThread=AfxBeginThread(Listen,&port);2.简单客户端/*#include#pragmacomment(lib,"WS2_32.lib")*/WSADATAwsd;SOCKETsHost;SOCKADDR_INservAddr;charbuf[1024]
6、;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_addr.s_addr=inet_addr(%%3);servAddr.sin_port=htons((short
7、)%%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,%%3);retVal=send(sHost,buf,sizeof(buf),0);if(SOCKET
8、_ERROR==retVal){closesocket(sHost);WSACleanup();return-1;//向服务器发送数据失败}closesocket(sHost);WSACleanup();3.获得本机IP/*#include#pragmacommen