12 if (net_ && sock_) net_->unbindUdpHost(sock_);
13 for (
UdpLink* l : owned_)
delete l;
22 if (!net_ || sock_)
return false;
24 if (!sock_ || !sock_->
bind(port)) {
29 net_->bindUdpHost(sock_,
this);
35 for (
auto& kv : byId_) kv.second->setLossRate(
rate);
40 for (
auto& kv : byId_) kv.second->setTimeoutMs(ms);
44 auto it = byAddr_.find(
from);
45 if (it != byAddr_.end()) {
50 auto* link =
new UdpLink(net_, sock_);
51 link->setRemoteString(
from);
52 const uint32_t
id = nextPeerId_++;
54 link->setLossRate(lossRate_);
55 link->setTimeoutMs(timeoutMs_);
56 link->setMessageHandler(
58 if (onMessage_) onMessage_(
id,
t, ch,
d,
n);
60 link->setDisconnectHandler([
this,
id](
const std::string&) {
61 pendingRemove_.push_back(
id);
65 owned_.push_back(link);
66 emitPeerConnected(
id);
71 pendingRemove_.clear();
72 for (
auto& kv : byId_) kv.second->pump(nowMs);
73 for (uint32_t
id : pendingRemove_) emitPeerDisconnected(
id);
77 auto it = byId_.find(peerId);
78 return it == byId_.end() ? nullptr : it->second;
82 const void* data,
size_t n) {
84 if (link) link->
send(
type, channel, data,
n);
88 const std::string&
s) {
93void NetHost::emitPeerConnected(uint32_t peerId) {
94 if (onConnect_) onConnect_(peerId);
96 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>(
"PlatformEvent");
98 std::vector<eve::platform_event::Variant> args;
105void NetHost::emitPeerDisconnected(uint32_t peerId) {
106 auto it = byId_.find(peerId);
107 if (it == byId_.end())
return;
108 UdpLink* link = it->second;
110 for (
auto a = byAddr_.begin();
a != byAddr_.end(); ++
a) {
111 if (
a->second == link) {
116 if (onDisconnect_) onDisconnect_(peerId);
118 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>(
"PlatformEvent");
120 std::vector<eve::platform_event::Variant> args;
bool sendStringTo(uint32_t peerId, UdpLink::MsgType type, uint8_t channel, const std::string &s)
Send string to.
void setLossRate(float rate)
Sets the loss rate.
void onDatagram(const std::vector< char > &bytes, const std::string &from)
On datagram.
void pump(int64_t nowMs)
Pump.
bool start(uint16_t port)
Starts .
void sendTo(uint32_t peerId, UdpLink::MsgType type, uint8_t channel, const void *data, size_t n)
Send to.
void setTimeoutMs(int ms)
Sets the timeout ms.
NetHost(Network *net)
Net host.
UdpLink * linkByPeerId(uint32_t peerId) const
Link by peer id.
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
UdpSocket * newUdp()
Script adapter: creates a caller-owned UDP socket.
EVENGINE_API_PLATFORM public API.
void send(MsgType type, uint8_t channel, const void *data, size_t n)
MsgType
MsgType public API.
bool sendString(MsgType type, uint8_t channel, const std::string &s)
bool bind(uint16_t port)
Binds to a local port; true on success.