agv-control/Plugin/KcCtrl/UdpSocket.h
2025-06-09 09:09:25 +08:00

75 lines
1.4 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
#include <iostream>
#include <string>
#include <cstring>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
class UDPServer {
private:
SOCKET serverSocket;
sockaddr_in serverAddr;
bool initialized;
void cleanup();
public:
UDPServer();
~UDPServer();
bool Start(int port);
// 修改后的接收方法UDPServer类
int Receive(char* buffer, int bufferSize, std::string& clientIP, int& clientPort);
bool Send(const char* buffer, int bufferSize, const std::string& clientIP, int clientPort);
void Close();
};
class UDPClient {
private:
SOCKET clientSocket;
sockaddr_in serverAddr;
bool initialized;
void cleanup();
public:
UDPClient();
~UDPClient();
bool Connect(const std::string& serverIP, int serverPort);
bool Send(const char* buffer, int bufferSize);
//lTimeoutMs 单位毫秒
int Receive(char* buffer, int bufferSize, int lTimeoutMs);
// sbuffer 发送数据
// sbufferSize 发送数据长度
// rbuffer 接收数据缓冲区
// rbufferSize 接收数据长度
// lRto 重传时间
// lRtoCnt 重传次数
// 返回值 接收数据长度,小于等于零表示发送以及重传都失败了
int SendAndRecv(const char* sbuffer, int sbufferSize, char* rbuffer, int rbufferSize, int lRto, int lRtoCnt);
void Close();
};