C++ UDP接收和发送
class UDP { public: UDP() { RecvAddrSize = sizeof(RecvAddr); int nResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (nResult != NO_ERROR) { std::cout << WSAGetLastError(); return; } RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //设置服务器地址 RecvAddr.sin_family = AF_INET; RecvAddr.sin_port = htons(Port); RecvAddr.sin_addr.s_addr = inet_addr("192.168.1.111"); int ret = bind(RecvSocket, (sockaddr *)&RecvAddr, sizeof(RecvAddr)); if (ret < 0) { perror("bind"); return; } } void sendDataToPython() {char temp[2000]; sprintf(temp, "insert into Flight_data.AirData({:}, cdata) values({:}, '{:}')", m_str, s_str, date_time); int flag = sendto(RecvSocket, temp, sizeof(temp), 0, (sockaddr*)&RecvAddr, sizeof(RecvAddr)); std::cout << flag; } } void recvDataToLocal() { memset(RecvBuf, '\0', sizeof(RecvBuf)); printf("recv a datagram to the receiver...\n"); int nResult = recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)&RecvAddr, &RecvAddrSize); //发送完成,关闭Socket printf("%s\n", RecvBuf); } ~UDP() { closesocket(RecvSocket); WSACleanup(); } private: WSADATA wsaData;//初始化 SOCKET RecvSocket; sockaddr_in RecvAddr, sendAddr;//服务器地址 char RecvBuf[10240] = { 0 };//发送数据的缓冲区 int Port = 4000;//服务器监听地址 int BufLen = 10240;//缓冲区大小 int RecvAddrSize = 0; //初始化SocketAddr的大小 };