资源描述:
《基于windows的socket编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、服务端发送和传输数据详解服务器发送数据时盥要知道客户端的IP地址和端11号TCP服务器端服务器发送数据时需要知道客户端的IP地址和端口号发送数据SocketSender::SocketSender(constString&_strlp,int_iPort){mstrip=strlp;//ip地址m_iPort=_iPort;//端口m_socket=INVALID_SOCKET;//定义一个无效的socketintibl,ib2,ib3,ib4,ib5,ib6;//6个IP地址swscanf_s(m_strlp.GetCString()
2、,_T("%d.%d.%d.%d.%d.%d"),&ibl,&ib2,&ib3,&ib4,&ib5,&ib6);memset(&m_addr,0,sizeof(maddr));maddr.sinfam订y=AFINET;m_addr.sin_port二htons((u_short)_iPort);(UCHAR)ibl(UCHAR)ib2(UCHAR)ib3(UCHAR)ib4m_addr.sin_addr.S_un.S_un_b.s_blmaddr.sinaddr.Sun.S_un_b.s_b2m_addr.sin_sddr.S_un.
3、S_un_b.s_b3m_addr.sin_sddr.S_un.S_un_b.s_b4WSADATAwsaD;memset(&wsal),0,sizeof(wsaD));:if(WSAStartup(0x101,&wsaD)!=0)//(版本号,获得特定WindowsSockets实现的细节,返回0表示成功){THROW_EXCEPTION(ExceptionWSAStartup(wsaD));//抛出异常}//创建socketm_socket二socket(AF_1NET,SOCK_STREAM,1PPROTO_TCP);if(m_s
4、ocket==INVALID_SOCKET){//如果是无效socket抛出异常THROWEXCEPTION(ExceptionSocketError());}//将参数m_socket连至参数m_addr指定的网络地址。建立连接(服务端socket,指向包含IP和端口号的扌旨针,m_3ddr的长度,与bind()参数一样)连接成功是返回0if(connect(m_sockct,(sockaddr*)&m_addr,sizeof(m_addr))!=0){THROW_EXCEPT1ON(ExceptionSocketError0);}S
5、ocketSender::^SocketSender(){join();//首先判断是否为无效的socket,有效时才可以进行关闭辻(m_socket匚INVAL1D_SOCKET){//关闭socket,成功关闭返四0if(closesocket(m_socket)!二0)THROWEXCEPTION(ExceptionSocketError());//清理成功返回0intiError=WSACleanupO;if(iError!=0)THROW_EXCEPTION(ExceptionWSAClcanup(iError));}}//发
6、送数据(socket,缓冲区,发送数据的大小,flag),若发送成功返回发送字符的总数,若失败返冋SOCKET_ERROR辻(send(msocket,(constchar*)ptr.get(),iBytesSend,0)==SOCKETERROR){THR0W_EXCEPT10N(ExceptionSocketError());)接收数据服务器接收数据时需耍客户端的端口号即可^include,zNotSocketRcccivor.h"namespaceSurveylonamespaceNety^T%rt%rY%片二〈十二y夕广rj%
7、耳卜"卜夕「*//Data接收器,子类必须使用new在堆上分配;^T*^T**T**T*^T*^T**y**T**y*^T**T**y**T**y**y**T*^T*^T**T^*y**
8、**T*^T*^T**
9、*^T**
10、**y*^T**T**T**T**T**T**T**T^*y*^T*voidDatallandler::Handle(constBYTE*pBuf,intiBytes){}*■”*1*•”•»•»*X*•+*L>•丄.•+•”・卜•”•”
11、*2>•”■”•丄*•”•”•丄■*?>•丄••]•*{*•+•”•丄・*X**1*•”•”・卜•丄*•”•»•丄■*{*■”*L>•丄・*L>•”*T*吩.*T**T**T*叫・