介绍

C++ Windows实现UDP Socket客户端
Windows IDE:Visual Studio 2022

支持库

#include <string>
#include <winsock2.h>
#include <WS2tcpip.h>

代码

main.h

#pragma once
#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <string>
#include <winsock2.h>
#include <WS2tcpip.h>

//添加动态库的lib
#pragma comment(lib, "ws2_32.lib")

class UDPSocketClient
{
private:
	SOCKET socketFD;
	SOCKADDR_IN serAddr; //远程地址
	WSADATA  wsaData;

public:
	UDPSocketClient();
	~UDPSocketClient();

	int connectServer(std::string ip, int port);
	int sendServerDate(std::string date);
	int getServerDate(std::string* buf);
	void closeConnect();

};

main.cpp

#include "main.h"

UDPSocketClient::UDPSocketClient()
{
	socketFD = 0;
	serAddr = {};
	if (WSAStartup(MAKEWORD(2, 2), &this->wsaData) < 0)
		exit;
}

UDPSocketClient::~UDPSocketClient()
{
	WSACleanup();
}

inline int UDPSocketClient::connectServer(std::string ip, int port)
{
	this->socketFD = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (this->socketFD == INVALID_SOCKET)
	{
		closesocket(this->socketFD);
		this->socketFD = INVALID_SOCKET;
		return -1;
	}

	// 远端地址
	this->serAddr.sin_family = AF_INET;
	this->serAddr.sin_port = htons(port);
	inet_pton(AF_INET, ip.c_str(), &this->serAddr.sin_addr);

	return 0;
}

inline int UDPSocketClient::sendServerDate(std::string date)
{
	int sendLen = sendto(this->socketFD, date.c_str(), date.size(), 0, (sockaddr*)&this->serAddr, sizeof(this->serAddr));
	return sendLen;
}

inline int UDPSocketClient::getServerDate(std::string* buf)
{
	char buffer[64]{};
	int len = 0;
	len = recvfrom(this->socketFD, buffer, 63, 0, NULL, NULL);
	buffer[len] = '\0';
	buf->append(buffer);
	return len;
}

inline void UDPSocketClient::closeConnect()
{
	closesocket(socketFD);
}

示例

#include <iostream>
#include "./main.h"

int main() {
    UDPSocketClient client;
    client.connectServer("192.168.222.1", 1001);
    client.sendServerDate("hello");
    std::string buf = "";
    std::string message = "";
    int len = 0;
    while(len = client.getServerDate(&buf) > 0){
        message.append(buf);
    }
    std::cout << message << std::endl;
    client.closeConnect();
    return 0;
}