improve packet interface
This commit is contained in:
94
src/blitz/network/EnetServer.cpp
Normal file
94
src/blitz/network/EnetServer.cpp
Normal file
@@ -0,0 +1,94 @@
|
||||
#include <blitz/network/EnetServer.h>
|
||||
|
||||
#include <Nazara/Core/ByteStream.hpp>
|
||||
|
||||
namespace blitz {
|
||||
namespace network {
|
||||
|
||||
EnetServer::EnetServer(std::uint16_t port) : m_Running(true) {
|
||||
m_Host.Create(Nz::NetProtocol::Any, port, 80);
|
||||
m_Host.AllowsIncomingConnections(true);
|
||||
m_Thread = std::thread(&EnetServer::WorkerThread, this);
|
||||
}
|
||||
|
||||
void EnetServer::WorkerThread() {
|
||||
while (m_Running) {
|
||||
Update();
|
||||
}
|
||||
}
|
||||
|
||||
EnetServer::~EnetServer() {
|
||||
if (m_Running)
|
||||
Destroy();
|
||||
}
|
||||
|
||||
void EnetServer::Update() {
|
||||
Nz::ENetEvent event;
|
||||
int service = m_Host.Service(&event, 5);
|
||||
if (service > 0) {
|
||||
do {
|
||||
switch (event.type) {
|
||||
case Nz::ENetEventType::Disconnect: {
|
||||
EnetConnexion* connexion = GetConnexion(event.peer->GetPeerId());
|
||||
if (!connexion)
|
||||
break;
|
||||
OnClientDisconnect(*connexion);
|
||||
break;
|
||||
}
|
||||
|
||||
case Nz::ENetEventType::DisconnectTimeout: {
|
||||
EnetConnexion* connexion = GetConnexion(event.peer->GetPeerId());
|
||||
if (!connexion)
|
||||
break;
|
||||
OnClientDisconnectTimeout(*connexion);
|
||||
break;
|
||||
}
|
||||
|
||||
case Nz::ENetEventType::IncomingConnect: {
|
||||
Nz::ENetPeer* peer = event.peer;
|
||||
m_Connexion.insert({peer->GetPeerId(), EnetConnexion(peer)});
|
||||
OnClientConnect(*GetConnexion(peer->GetPeerId()));
|
||||
break;
|
||||
}
|
||||
|
||||
case Nz::ENetEventType::Receive: {
|
||||
EnetConnexion* connexion = GetConnexion(event.peer->GetPeerId());
|
||||
if (!connexion)
|
||||
break;
|
||||
connexion->Recieve(event.packet.m_packet->data);
|
||||
break;
|
||||
}
|
||||
|
||||
case Nz::ENetEventType::OutgoingConnect:
|
||||
case Nz::ENetEventType::None:
|
||||
break;
|
||||
}
|
||||
} while (m_Host.CheckEvents(&event));
|
||||
}
|
||||
}
|
||||
|
||||
EnetConnexion* EnetServer::GetConnexion(std::uint16_t a_PeerId) {
|
||||
auto it = m_Connexion.find(a_PeerId);
|
||||
|
||||
if (it == m_Connexion.end())
|
||||
return nullptr;
|
||||
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
void EnetServer::BroadcastPacket(const protocol::Packet& a_Packet, Nz::ENetPacketFlags a_Flags) {
|
||||
// m_Host.Broadcast(0, a_Flags, std::move(a_Data));
|
||||
}
|
||||
|
||||
void EnetServer::RemoveConnexion(std::uint16_t a_PeerId) {
|
||||
m_Connexion.erase(a_PeerId);
|
||||
}
|
||||
|
||||
void EnetServer::Destroy() {
|
||||
m_Running = false;
|
||||
m_Thread.join();
|
||||
m_Host.Destroy();
|
||||
}
|
||||
|
||||
} // namespace network
|
||||
} // namespace blitz
|
||||
Reference in New Issue
Block a user