資源描述:
《基于windows的socket編程》由會員上傳分享,免費在線閱讀,更多相關內(nèi)容在工程資料-天天文庫。
1、服務端發(fā)送和傳輸數(shù)據(jù)詳解服務器發(fā)送數(shù)據(jù)時盥要知道客戶端的IP地址和端11號TCP服務器端服務器發(fā)送數(shù)據(jù)時需要知道客戶端的IP地址和端口號發(fā)送數(shù)據(jù)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實現(xiàn)的細節(jié),返回0表示成功){THROW_EXCEPTION(ExceptionWSAStartup(wsaD));//拋出異常}//創(chuàng)建socketm_socket二socket(AF_1NET,SOCK_STREAM,1PPROTO_TCP);if(m_s
4、ocket==INVALID_SOCKET){//如果是無效socket拋出異常THROWEXCEPTION(ExceptionSocketError());}//將參數(shù)m_socket連至參數(shù)m_addr指定的網(wǎng)絡地址。建立連接(服務端socket,指向包含IP和端口號的扌旨針,m_3ddr的長度,與bind()參數(shù)一樣)連接成功是返回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));}}//發(fā)
6、送數(shù)據(jù)(socket,緩沖區(qū),發(fā)送數(shù)據(jù)的大小,flag),若發(fā)送成功返回發(fā)送字符的總數(shù),若失敗返冋SOCKET_ERROR辻(send(msocket,(constchar*)ptr.get(),iBytesSend,0)==SOCKETERROR){THR0W_EXCEPT10N(ExceptionSocketError());)接收數(shù)據(jù)服務器接收數(shù)據(jù)時需??蛻舳说亩丝谔柤纯蒦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*叫?