資源描述:
《window基于TCP、UDP通信》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、VC++?使用socket基于TCP、UDP通信?(2012-12-1813:05:36)轉(zhuǎn)載▼標(biāo)簽:?socket?bind?listen?send?recv分類:?TCP/IP首先包含頭文件:#include鏈接winsock庫(kù)#pragmacomment(lib,"ws2_32.lib")#defineMAX_MSG_LEN1500//最大的消息長(zhǎng)度(MTU)TCP方式通信(服務(wù)端):1、加載SOCKET庫(kù)WSADATAwsa;if(WSAStartup(MAKEWORD(1,1)
2、,&wsa)!=0){returnFALSE;??//加載失敗}2、創(chuàng)建SOCKETSOCKETm_socket=socket(AF_INET,SOCK_STREAM,0);//TCP流式3、將SOCKET綁定到IP和端口//配置監(jiān)聽(tīng)地址、綁定監(jiān)聽(tīng)端口?SOCKADDR_INSersock;//用于服務(wù)器的監(jiān)聽(tīng)SOCKETZeroMemory(&Sersock,sizeof(Sersock));?Sersock.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//所有可用IPSe
3、rsock.sin_family=AF_INET;?Sersock.sin_port=htons(usPort);//端口號(hào)?intnbind=?bind(m_socket,(SOCKADDR*)&Sersock,sizeof(SOCKADDR));?if(SOCKET_ERROR==nbind)?{??closesocket(m_socket);?returnFALSE;?}4、創(chuàng)建線程,設(shè)置創(chuàng)建的SOCKET為監(jiān)聽(tīng)模式等待連接請(qǐng)求listen(m_socket,5);5、使用accept函數(shù)接收到一個(gè)請(qǐng)求
4、后(在接收到請(qǐng)求后才會(huì)返回),將創(chuàng)建一個(gè)與客戶端新的SOCKET。6、使用新的SOCKET與客戶端send/recv通信。7、關(guān)閉本次連接SOCKADDR_INaddrClient;intlen=sizeof(SOCKADDR);charszrecvbuf[MAX_MSG_LEN];charszsendBuf[50];ZeroMemory(szrecvbuf,sizeof(szrecvbuf));ZeroMemory(szsendBuf,sizeof(szsendBuf));SOCKETsockSer;whi
5、le(TRUE){//用accept函數(shù)接收客戶方的連接sockSer=accept(m_socket,(SOCKADDR*)&addrClient,&len);if(INVALID_SOCKET==sockSer)continue;sprintf(szsendBuf,"Welcome%stoThis!",inet_ntoa(addrClient.sin_addr));//在客戶方套接字clientSocket上使用send發(fā)送數(shù)據(jù)send(sockSer,szsendBuf,strlen(szsendBuf
6、)+1,0);//接收的數(shù)據(jù)recv(sockSer,szrecvbuf,50,0);psocket->m_strData.Format(_T("IP:%s,端口:%d說(shuō):%s"),inet_ntoa(addrClient.sin_addr),addrClient.sin_port,szrecvbuf);//::PostMessage(hwnd,WM_RECVDATA,0,(LPARAM)psocket->m_strData.GetBuffer(0));//(給窗口發(fā)消息,通知)//關(guān)閉本次連接closeso
7、cket(sockSer);//休息100SSleep(100);}8、關(guān)閉SOCKET和釋放SOCKET庫(kù)//關(guān)閉socketclosesocket(m_socket);WSACleanup();TCP方式通信(客戶端):1、加載SOCKET庫(kù)WSADATAwsa;if(WSAStartup(MAKEWORD(1,1),&wsa)!=0){returnFALSE;??//加載失敗}2、創(chuàng)建SOCKETSOCKETm_socket=socket(AF_INET,SOCK_STREAM,0);//TCP流式3、
8、向服務(wù)端發(fā)送連接請(qǐng)求SOCKADDR_INSocketSendIn;SocketSendIn.sin_family=AF_INET;SocketSendIn.sin_addr.S_un.S_addr=htonl(m_ulRemoteIP);SocketSendIn.sin_port=htons(m_usRemotePort);charszBuf[50];//先建立連接intnRet=?connect