#C++UDP使用示例
#include <iostream>
#include "Winsock2.h"
#include<vector>
#include<string>
#pragma comment(lib,"WS2_32.lib")//链接Ws2_32.lib库
#pragma pack(1)//结构体 1 字节对齐
struct ReturnDEMINFO
{
ReturnDEMINFO(int id, double alt)
{
_Id = id; _Alt = alt;
}
int _Id;
float _Alt;
};
SOCKET mSocket;
SOCKADDR_IN mAddrLocal;
SOCKADDR_IN mAddrRemote;
int main()
{
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(2, 2);
if (WSAStartup(wVersionRequested, &wsaData) == SOCKET_ERROR)
{
std::cout << "1" << std::endl;
return FALSE;
}
mAddrLocal.sin_family = AF_INET;
mAddrLocal.sin_port = htons(30002);
mAddrLocal.sin_addr.s_addr = inet_addr("0.0.0.0");
mAddrRemote.sin_family = AF_INET;
mAddrRemote.sin_port = htons(10008);
mAddrRemote.sin_addr.s_addr = inet_addr("127.0.0.1");
if ((mSocket = socket(AF_INET, SOCK_DGRAM, 0)) == ERROR)
{
std::cout << "1" << std::endl;
perror("socket() error\n");
return FALSE;
}
int nSockAddrSize = sizeof(struct sockaddr_in);
if (bind(mSocket, (struct sockaddr *)&mAddrLocal, nSockAddrSize) == SOCKET_ERROR)
{
std::cout << "3" << std::endl;
perror("bind error\n");
return FALSE;
}
while (true)
{
unsigned long socketMode = 0;
ioctlsocket(mSocket, FIOASYNC, &socketMode);
char ch[64] = { 0 };
int iRecvSize = recvfrom(mSocket, ch, 64, 0, (struct sockaddr *)&mAddrLocal, &nSockAddrSize);
if (iRecvSize < 0) continue;
std::cout << 111 << std::endl;
ReturnDEMINFO ri(0,0);
memcpy((char*)&ri, ch, sizeof(ReturnDEMINFO));
std::cout << ri._Alt << " "<<ri._Id << std::endl;
}
}