4#include <simplesquirrel/simplesquirrel.hpp>
20 if (net_ && sock_) net_->unbindUdpHost(sock_);
21 for (
UdpLink* l : owned_)
delete l;
30 if (!net_ || sock_)
return false;
32 if (!sock_ || !sock_->
bind(port)) {
37 net_->bindUdpHost(sock_,
this);
43 for (
auto& kv : byId_) kv.second->setLossRate(
rate);
48 for (
auto& kv : byId_) kv.second->setTimeoutMs(ms);
52 auto it = byAddr_.find(
from);
53 if (it != byAddr_.end()) {
60 const uint32_t
id = nextPeerId_++;
62 link->setLossRate(lossRate_);
63 link->setTimeoutMs(timeoutMs_);
65 if (onMessage_) onMessage_(
id,
t, ch,
d,
n);
67 link->setDisconnectHandler([
this,
id](
const std::string&) { pendingRemove_.push_back(
id); });
70 owned_.push_back(
link);
71 emitPeerConnected(
id);
76 pendingRemove_.clear();
77 for (
auto& kv : byId_) kv.second->pump(nowMs);
78 for (uint32_t
id : pendingRemove_) emitPeerDisconnected(
id);
82 auto it = byId_.find(peerId);
83 return it == byId_.end() ? nullptr : it->second;
96void NetHost::emitPeerConnected(uint32_t peerId) {
97 if (onConnect_) onConnect_(peerId);
99 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>(
"PlatformEvent");
101 std::vector<eve::platform_event::Variant> args;
108void NetHost::emitPeerDisconnected(uint32_t peerId) {
109 auto it = byId_.find(peerId);
110 if (it == byId_.end())
return;
111 UdpLink*
link = it->second;
113 for (
auto a = byAddr_.begin();
a != byAddr_.end(); ++
a) {
114 if (
a->second ==
link) {
119 if (onDisconnect_) onDisconnect_(peerId);
121 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>(
"PlatformEvent");
123 std::vector<eve::platform_event::Variant> args;
137void callScriptFn(
const ssq::Object&
fn,
const std::string& arg) {
138 if (
fn.isEmpty())
return;
139 ssq::Function
f =
fn.toFunction();
140 if (
f.isEmpty())
return;
151 onLinkMessage(
type, channel, data,
n);
160void NetRpc::call(uint16_t msgId,
const void* data,
size_t n,
bool reliable) {
161 if (!link_ || (data ==
nullptr &&
n > 0))
return;
162 std::vector<char> env;
163 env.push_back(
static_cast<char>(msgId & 0xff));
164 env.push_back(
static_cast<char>((msgId >> 8) & 0xff));
165 const char*
p =
static_cast<const char*
>(data);
166 env.insert(env.end(),
p,
p +
n);
171 if (!link_)
return false;
179 if (
fn.isEmpty())
return;
180 scriptHandlers_[msgId] =
fn;
185 if (channel != 0 ||
n < 2)
return;
186 const uint16_t msgId =
static_cast<uint16_t
>(uint8_t(data[0])) | (
static_cast<uint16_t
>(uint8_t(data[1])) << 8);
187 const char*
payload = data + 2;
188 const size_t payloadLen =
n - 2;
190 auto sit = scriptHandlers_.find(msgId);
191 if (sit != scriptHandlers_.end()) {
192 callScriptFn(sit->second, std::string(
payload, payloadLen));
195 auto it = handlers_.find(msgId);
196 if (it == handlers_.end())
return;
197 NetReader reader(
payload, payloadLen);
208void putLe16(std::vector<char>& buf, uint16_t
v) {
209 buf.push_back(
static_cast<char>(
v & 0xff));
210 buf.push_back(
static_cast<char>((
v >> 8) & 0xff));
213void putLe32(std::vector<char>& buf, uint32_t
v) {
214 buf.push_back(
static_cast<char>(
v & 0xff));
215 buf.push_back(
static_cast<char>((
v >> 8) & 0xff));
216 buf.push_back(
static_cast<char>((
v >> 16) & 0xff));
217 buf.push_back(
static_cast<char>((
v >> 24) & 0xff));
220void putLe64(std::vector<char>& buf, uint64_t
v) {
221 for (
int i = 0; i < 8; ++i) {
222 buf.push_back(
static_cast<char>((
v >> (8 * i)) & 0xff));
226uint16_t getLe16(
const char*
p) {
227 return static_cast<uint16_t
>(uint8_t(
p[0])) | (
static_cast<uint16_t
>(uint8_t(
p[1])) << 8);
230uint32_t getLe32(
const char*
p) {
231 return static_cast<uint32_t
>(uint8_t(
p[0])) | (
static_cast<uint32_t
>(uint8_t(
p[1])) << 8) |
232 (
static_cast<uint32_t
>(uint8_t(
p[2])) << 16) | (
static_cast<uint32_t
>(uint8_t(
p[3])) << 24);
235uint64_t getLe64(
const char*
p) {
237 for (
int i = 0; i < 8; ++i) {
238 v |= (uint64_t(uint8_t(
p[i])) << (8 * i));
245void NetWriter::put(
const void*
d,
size_t n) {
246 if (!
d ||
n == 0)
return;
247 const char*
p =
static_cast<const char*
>(
d);
248 buf_.insert(buf_.end(),
p,
p +
n);
269 static_assert(
sizeof(bits) ==
sizeof(
v),
"float must be 32-bit");
270 std::memcpy(&bits, &
v,
sizeof(bits));
276 static_assert(
sizeof(bits) ==
sizeof(
v),
"double must be 64-bit");
277 std::memcpy(&bits, &
v,
sizeof(bits));
284 putLe32(buf_,
static_cast<uint32_t
>(
s.size()));
285 put(
s.data(),
s.size());
289 putLe32(buf_,
static_cast<uint32_t
>(
n));
298 if (
d ==
nullptr &&
n != 0) {
302 data_ =
static_cast<const char*
>(
d);
309bool NetReader::take(
void*
out,
size_t n) {
310 if (!ok_)
return false;
311 if (
n > size_ - pos_) {
315 if (
out &&
n > 0) std::memcpy(
out, data_ + pos_,
n);
322 return size_ >= pos_ ? size_ - pos_ : 0;
338 char tmp[2] = {0, 0};
339 if (!take(tmp, 2))
return 0;
346 char tmp[4] = {0, 0, 0, 0};
347 if (!take(tmp, 4))
return 0;
354 char tmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
355 if (!take(tmp, 8))
return 0;
362 uint32_t bits =
u32();
364 std::memcpy(&
v, &bits,
sizeof(
v));
369 uint64_t bits =
u64();
371 std::memcpy(&
v, &bits,
sizeof(
v));
382 if (!take(
out.data(),
n)) {
390 std::vector<char>
out;
391 uint32_t len =
u32();
397 if (!take(
out.data(),
n))
out.clear();
411 if (running_)
return;
413 thread_ = std::thread([
this] { threadMain(); });
421 if (thread_.joinable() && thread_.get_id() != std::this_thread::get_id()) thread_.join();
425 std::lock_guard<std::mutex> lock(mu_);
426 completions_.push_back(std::move(
c));
430 std::lock_guard<std::mutex> lock(mu_);
431 out.swap(completions_);
436 std::lock_guard<std::mutex> lock(mu_);
437 jobs_.push_back(std::move(job));
442void NetWorker::threadMain() {
444 std::vector<std::function<void()>> batch;
446 std::unique_lock<std::mutex> lock(mu_);
447 cv_.wait_for(lock, std::chrono::milliseconds(5), [
this] {
return !running_ || !jobs_.empty(); });
448 if (!running_ && jobs_.empty())
break;
451 for (
auto& job : batch) {
454 if (owner_) owner_->pollSockets();
std::shared_ptr< OceanGpuSpectrum > owner
The single Squirrel projection for common Result, Status and Value.
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.
size_t remaining() const
Remaining.
std::vector< char > bytes(size_t n)
Bytes.
NetReader()=default
Net reader.
bool init(const void *d, size_t n)
Initializes .
void registerScript(uint16_t msgId, ssq::Object fn)
Registers script.
void registerHandler(uint16_t msgId, Handler h)
Registers handler.
bool callString(uint16_t msgId, const std::string &payload, bool reliable=true)
Call string.
std::function< void(NetReader &)> Handler
NetRpc(UdpLink *link)
Net rpc.
void call(uint16_t msgId, const void *data, size_t n, bool reliable=true)
Call.
void drain(std::vector< NetCompletion > &out)
Test helper: moves all pending completions into out.
void post(NetCompletion c)
Queues a completion for the main thread (thread-safe).
void stop()
Stops the worker thread and joins it.
NetWorker(Network *owner)
Creates a worker owned by owner (not started yet).
void start()
Starts the worker thread.
void submit(std::function< void()> job)
Queues an arbitrary blocking job to run on the worker thread.
void writeBool(bool v)
Writes bool.
void writeU8(uint8_t v)
Writes u 8.
void writeI64(int64_t v)
Writes i 64.
void writeBytes(const void *d, size_t n)
Writes bytes.
void writeF32(float v)
Writes f 32.
void writeI16(int16_t v)
Writes i 16.
void writeString(const std::string &s)
Writes string.
void writeI32(int32_t v)
Writes i 32.
void writeF64(double v)
Writes f 64.
void writeI8(int8_t v)
Writes i 8.
void writeU64(uint64_t v)
Writes u 64.
void writeU16(uint16_t v)
Writes u 16.
void writeU32(uint32_t v)
Writes u 32.
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.
void setMessageHandler(MessageHandler h)
bool bind(uint16_t port)
Binds to a local port; true on success.
SQRESULT callFunction(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
Call a script function, deriving sq_call's parameter count from the pushes.
constexpr RootTable rootTable
SettlementPipeline::Stage fn
One asynchronous network result/event. handle points at the originating TcpSocket/UdpSocket/HttpReque...