C++UDP使用示例

#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;	
	}




}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值