首页 > 代码库 > UDP发送和接收
UDP发送和接收
MainRecv.cpp
#include <iostream> #include <WinSock2.h> #include <sstream> #pragma comment(lib,"ws2_32.lib") #define RECV_IP "127.0.0.1" #define RECV_PORT 8899 #define LEN_RECV_BUF 2048 int main() { std::ostringstream ossTemp; WSAData wsaData; std::cout<<"Start..."<<std::endl; WSAStartup(MAKEWORD(2,2),&wsaData); SOCKET sktRecv=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); sockaddr_in addrRecv; addrRecv.sin_family=AF_INET; addrRecv.sin_addr.s_addr=inet_addr(RECV_IP); //htonl(INADDR_ANY); addrRecv.sin_port=htons(RECV_PORT); int retVal; retVal=bind(sktRecv,(sockaddr*)&addrRecv,sizeof(addrRecv)); sockaddr_in addrClient; char buf[LEN_RECV_BUF]; int len=sizeof(addrClient); while(true) { memset(buf,0,LEN_RECV_BUF); retVal=recvfrom(sktRecv,buf,LEN_RECV_BUF,0,(sockaddr*)&addrClient,&len); if(SOCKET_ERROR==retVal) { ossTemp<<"recvfrom error : "<<retVal<<"\n"; OutputDebugString(ossTemp.str().c_str()); break; } if(strlen(buf)>0) std::cout<<buf<<std::endl; } closesocket(sktRecv); WSACleanup(); std::cout<<"Recv Over"<<std::endl; getchar(); return -1; }
MainSend.cpp
#include <iostream> #include <sstream> #include <WinSock2.h> #define IP_SEND "127.0.0.1" #define PORT_SEND 8899 #define LEN_SEND_BUF 1024 #pragma comment(lib,"ws2_32.lib") int main() { WSAData wsaData; WSAStartup(MAKEWORD(2,2),&wsaData); std::cout<<"Begin Sending..."<<std::endl; std::ostringstream ossTemp; SOCKET sktSend=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); sockaddr_in addrSend; addrSend.sin_family=AF_INET; addrSend.sin_addr.s_addr=inet_addr(IP_SEND); addrSend.sin_port=htons(PORT_SEND); int retVal; char buf[LEN_SEND_BUF]; int len=sizeof(addrSend); int index=0; while(true) { if(index>255) break; ossTemp.str(""); ossTemp<<index; memset(buf,0,LEN_SEND_BUF); memcpy(buf,ossTemp.str().c_str(),sizeof(int)); retVal=sendto(sktSend,buf,LEN_SEND_BUF,0,(sockaddr*)&addrSend,len); if(SOCKET_ERROR==retVal) { ossTemp.str(""); ossTemp<<"sendto error : "<<retVal; OutputDebugString( ossTemp.str().c_str() ); break; } std::cout<<"Send : "<<buf<<std::endl; index++; } closesocket(sktSend); WSACleanup(); std::cout<<"Send Over"<<std::endl; getchar(); return 0; }
设置端口缓存大小:
//2. may set socket behavior
int nErrCode;
unsigned int uiRcvBuf;
int uiRcvBufLen = sizeof(uiRcvBuf);
nErrCode= getsockopt(m_tcpClient, SOL_SOCKET, SO_RCVBUF, (char*)&uiRcvBuf, &uiRcvBufLen);
if(SOCKET_ERROR == nErrCode) return FALSE;
if(uiRcvBuf!=1024*8){
//uiRcvBuf *= BUF_MULTIPLE;
uiRcvBuf=1024*8;
nErrCode = setsockopt(m_tcpClient, SOL_SOCKET, SO_RCVBUF,(char*)&uiRcvBuf, uiRcvBufLen);
if (SOCKET_ERROR == nErrCode) return FALSE;
nErrCode=getsockopt(m_tcpClient, SOL_SOCKET, SO_RCVBUF,(char*)&uiRcvBuf, &uiRcvBufLen);
if (SOCKET_ERROR == nErrCode) return FALSE;
if(uiRcvBuf!=1024*8) return FALSE;
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。