c++ udp通信发送.rar

时间:2017-05-20 09:53:54
【文件属性】:

文件名称:c++ udp通信发送.rar

文件大小:5.93MB

文件格式:RAR

更新时间:2017-05-20 09:53:54

c++ udp 通信

c++ udp通信发送实例 ///////////////////////////////////////////////////////// // initsock.h文件 #include #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib class CInitSock { public: CInitSock(BYTE minorVer = 2, BYTE majorVer = 2) { // 初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion, &wsaData) != 0) { exit(0); } } ~CInitSock() { ::WSACleanup(); } }; ////////////////////////////////////////////////////////// // UDPClient文件 #include "../common/InitSock.h" #include CInitSock initSock; // 初始化Winsock库 int main() { // 创建套节字 SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(s == INVALID_SOCKET) { printf("Failed socket() %d \n", ::WSAGetLastError()); return 0; } // 也可以在这里调用bind函数绑定一个本地地址 // 否则系统将会自动安排 // 填写远程地址信息 sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(4567); // 注意,这里要填写服务器程序所在机器的IP地址 // 如果你的计算机没有联网,直接使用127.0.0.1即可 addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); // 发送数据 char szText[] = " TCP Server Demo! \r\n"; ::sendto(s, szText, strlen(szText), 0, (sockaddr*)&addr, sizeof(addr)); ::closesocket(s); return 0; } ////////////////////////////////////////////////////////// // UDPServer.cpp文件 #include "../common/InitSock.h" #include CInitSock initSock; // 初始化Winsock库 int main() { // 创建套节字 SOCKET s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(s == INVALID_SOCKET) { printf("Failed socket() \n"); return 0; } // 填充sockaddr_in结构 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(4567); sin.sin_addr.S_un.S_addr = INADDR_ANY; // 绑定这个套节字到一个本地地址 if(::bind(s, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("Failed bind() \n"); return 0; } // 接收数据 char buff[1024]; sockaddr_in addr; int nLen = sizeof(addr); while(TRUE) { int nRecv = ::recvfrom(s, buff, 1024, 0, (sockaddr*)&addr, &nLen); if(nRecv > 0) { buff[nRecv] = '\0'; printf(" 接收到数据(%s):%s", ::inet_ntoa(addr.sin_addr), buff); } } ::closesocket(s); }


【文件预览】:
c++ udp通信发送
----Debug()
--------tttttttttttt.ilk(326KB)
--------tttttttttttt.pdb(563KB)
--------tttttttttttt.exe(37KB)
----ipch()
--------tttttttttttt-276f25e5()
----tttttttttttt.sdf(24.21MB)
----tttttttttttt.sln(903B)
----tttttttttttt()
--------tttttttttttt.cpp(1KB)
--------Debug()
--------stdafx.h(233B)
--------ReadMe.txt(2KB)
--------tttttttttttt.vcxproj.filters(1KB)
--------stdafx.cpp(217B)
--------tttttttttttt.vcxproj.user(143B)
--------tttttttttttt.vcxproj(4KB)
--------targetver.h(236B)
----tttttttttttt.suo(1.53MB)
----C++udp通信.doc(18KB)

网友评论

  • 还不错,可以参考
  • 还不错,可以参考