75 lines
1.4 KiB
C++
75 lines
1.4 KiB
C++
#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();
|
||
};
|