Files
Lixinzhe_lib/Socket/UDP.h

96 lines
2.0 KiB
C
Raw Permalink Normal View History

2025-06-16 08:52:40 +08:00
#ifndef LXZL_UDP_H
#define LXZL_UDP_H
#include "NetworkRelated.h"
#include <iostream>
#include <vector>
#include <functional>
#include <thread>
#include <atomic>
//定义UDP接收线程超时时间(秒)
#define UDPTimeout (3)
/**
* UDP基类
*/
class UDPSocketBase {
protected:
UDPSocketBase() : sockfd_(INVALID_SOCKET_VALUE), is_nonblock_(false) {}
/** 创建套接字 */
void create_socket();
void create_socket(socket_t socket);
/** 设置是否阻塞 */
void set_nonblock(bool enable);
/** 建立链接 */
void bind_socket(const sockaddr_in &addr) const;
public:
virtual ~UDPSocketBase();
socket_t sockfd_;
protected:
bool is_nonblock_;
};
/**
* UDP发送端
*/
class UDPSender : public UDPSocketBase {
public:
explicit UDPSender(socket_t socket=INVALID_SOCKET_VALUE,bool nonblock = false);
/** 设置目的地址 */
void set_destination(const std::string &ip, uint16_t port);
/** 设置源地址 */
void set_source(const std::string &ip, uint16_t port);
/** 发送 */
size_t send(const std::vector<uint8_t> &data);
size_t send(uint8_t *data, size_t size);
size_t send(const std::string &data);
std::string dstIp;
uint16_t dstPort;
private:
sockaddr_in dest_addr_{};
};
/**
* UDP接收端
*/
class UDPReceiver : public UDPSocketBase {
public:
/** 处理接收数据函数模板 */
using ReceiveCallback = std::function<void(const std::vector<uint8_t> &, sockaddr_in, socklen_t)>;
/** 设置接收端口 */
explicit UDPReceiver(uint16_t port, bool nonblock = false, size_t buffer_size = 4096);
/** 开始接收线程 */
void start_receiving(const ReceiveCallback &callback);
/** 停止接收线程 */
void stop_receiving();
uint16_t srcPort;
private:
/** 接收函数 */
std::pair<ssize_t, std::pair<sockaddr_in, socklen_t>> receive();
private:
std::vector<uint8_t> buffer_;
std::atomic<bool> running_;
std::thread receiver_thread_;
};
#endif //LXZL_UDP_H