Files
CPP_Core/Socket_old/UDP_Client.cpp
T
2026-06-16 10:56:40 +08:00

83 lines
1.9 KiB
C++
Raw 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.
// UDP_Client.cpp
#include "UDP_Client.h"
namespace Psc::socket {
void UDP_Client::create() {
// 关闭旧 fd
if (socket_fd != -1) {
(void)socket::close(socket_fd);
socket_fd = -1;
}
connected = false;
auto rsf = socket::create_socket_fd(Socket_Type::UDP);
if (!rsf) {
// 你工程里有 logger 的话在这里打日志;否则静默失败
return;
}
socket_fd = rsf.value();
// 常见选项(失败也不致命:按你的风格你可以选择 fail_fast 或记录日志后 return
auto r = socket::set_reuse(socket_fd, true).and_then([this]() {
return socket::set_block(socket_fd, false);
});
if (!r) {
socket_logger->c_debug({}, {}, to_string() + "设置属性失败,强制退出!");
}
}
bool UDP_Client::connect() {
if (socket_fd == -1) {
create();
if (socket_fd == -1) return false;
}
auto r = socket::connect(socket_fd, dest_address);
if (!r) {
connected = false;
return false;
}
connected = r.value(); // 通常为 true
return connected;
}
std::string UDP_Client::read() {
if (socket_fd == -1) return {};
Sockaddr_In peer{};
auto r = socket::UDP::recvfrom(socket_fd, &peer, read_chunk_size);
if (!r) {
// 这里可以按需:返回空串 / 抛异常 / 记录日志
return {};
}
return r.value();
}
void UDP_Client::send(const std::string& data) {
if (socket_fd == -1) {
create();
if (socket_fd == -1) return;
}
// 为了不依赖 Sockaddr_In 的 ip/port 字段,这里走 “UDP connect + send()”
if (!connected) {
if (!connect()) return;
}
(void)socket::send(socket_fd, data);
}
void UDP_Client::close() {
if (socket_fd != -1) {
(void)socket::close(socket_fd);
socket_fd = -1;
}
connected = false;
state = Not_Created;
}
std::string UDP_Client::to_string() {
return VAR_STR_5(dest_address.to_string(), socket_fd, connected, blocking, read_chunk_size);
}
} // namespace Psc::socket