载入中...
搜索中...
未找到
NetHost.h
浏览该文件的文档.
1#pragma once
2#include "common/Export.h"
3
4
5#include "network/UdpLink.h"
6
7#include <cstdint>
8#include <functional>
9#include <string>
10#include <unordered_map>
11#include <vector>
12
13namespace eve::network {
14
15class Network;
16class UdpSocket;
17
26public:
28 explicit NetHost(Network* net);
30 ~NetHost();
31
33 bool start(uint16_t port);
35 void setLossRate(float rate);
37 void setTimeoutMs(int ms);
38
40 void onDatagram(const std::vector<char>& bytes, const std::string& from);
42 void pump(int64_t nowMs);
43
45 UdpLink* linkByPeerId(uint32_t peerId) const;
47 size_t peerCount() const { return byId_.size(); }
48
50 void sendTo(uint32_t peerId, UdpLink::MsgType type, uint8_t channel,
51 const void* data, size_t n);
53 bool sendStringTo(uint32_t peerId, UdpLink::MsgType type, uint8_t channel,
54 const std::string& s);
55
56 using MessageHandler = std::function<void(uint32_t peerId, UdpLink::MsgType,
57 uint8_t channel, const char*, size_t)>;
58 using PeerHandler = std::function<void(uint32_t peerId)>;
59
61 void setMessageHandler(MessageHandler h) { onMessage_ = std::move(h); }
63 void setPeerConnectedHandler(PeerHandler h) { onConnect_ = std::move(h); }
65 void setPeerDisconnectedHandler(PeerHandler h) { onDisconnect_ = std::move(h); }
66
67private:
68 void emitPeerConnected(uint32_t peerId);
69 void emitPeerDisconnected(uint32_t peerId);
70
71 Network* net_ = nullptr;
72 UdpSocket* sock_ = nullptr;
73 std::unordered_map<std::string, UdpLink*> byAddr_;
74 std::unordered_map<uint32_t, UdpLink*> byId_;
75 std::vector<UdpLink*> owned_;
76 std::vector<uint32_t> pendingRemove_;
77 uint32_t nextPeerId_ = 1;
78 float lossRate_ = 0.f;
79 int timeoutMs_ = 10000;
80 MessageHandler onMessage_;
81 PeerHandler onConnect_;
82 PeerHandler onDisconnect_;
83};
84
85} // namespace eve::network
Duration start
std::string from
const std::string & s
#define EVENGINE_API_PLATFORM
Definition Export.h:107
glm::vec3 n
Definition Grass.cpp:63
int h
std::uint64_t bytes
EVENGINE_API_PLATFORM public API.
Definition NetHost.h:25
void setMessageHandler(MessageHandler h)
Sets the message handler.
Definition NetHost.h:61
std::function< void(uint32_t peerId, UdpLink::MsgType, uint8_t channel, const char *, size_t)> MessageHandler
Definition NetHost.h:57
std::function< void(uint32_t peerId)> PeerHandler
Definition NetHost.h:58
size_t peerCount() const
Peer count.
Definition NetHost.h:47
void setPeerConnectedHandler(PeerHandler h)
Sets the peer connected handler.
Definition NetHost.h:63
void setPeerDisconnectedHandler(PeerHandler h)
Sets the peer disconnected handler.
Definition NetHost.h:65
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
Definition Network.h:35
UDP socket backed by Poco::Net; supports connect/bind and datagram send.
Definition UdpSocket.h:26