Network: Add support for sending/receiving NetPacket over UDP/TCP
Former-commit-id: 5c09a5fa8b499e4204d2312f6d04d8554093a5a4
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
// For conditions of distribution and use, see copyright notice in Config.hpp
|
||||
|
||||
#include <Nazara/Network/UdpSocket.hpp>
|
||||
#include <Nazara/Network/NetPacket.hpp>
|
||||
|
||||
#if defined(NAZARA_PLATFORM_WINDOWS)
|
||||
#include <Nazara/Network/Win32/SocketImpl.hpp>
|
||||
@@ -61,6 +62,43 @@ namespace Nz
|
||||
return true;
|
||||
}
|
||||
|
||||
bool UdpSocket::ReceivePacket(NetPacket* packet, IpAddress* from)
|
||||
{
|
||||
// I'm not sure what's the best between having a 65k bytes buffer ready for any datagram size
|
||||
// or querying the next datagram size every time, for now I'll leave it as is
|
||||
packet->Reset(NetCode_Invalid, std::numeric_limits<UInt16>::max());
|
||||
|
||||
std::size_t received;
|
||||
if (!Receive(packet->GetData(), static_cast<std::size_t>(packet->GetSize()), from, &received))
|
||||
{
|
||||
NazaraError("Failed to receive packet");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (received == 0)
|
||||
return false; //< No datagram received
|
||||
|
||||
Nz::UInt16 netCode;
|
||||
Nz::UInt16 packetSize;
|
||||
if (!NetPacket::DecodeHeader(packet->GetConstData(), &packetSize, &netCode))
|
||||
{
|
||||
m_lastError = SocketError_Packet;
|
||||
NazaraWarning("Invalid header data");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (packetSize != received)
|
||||
{
|
||||
m_lastError = SocketError_Packet;
|
||||
NazaraWarning("Invalid packet size (packet size is " + String::Number(packetSize) + " bytes, received " + Nz::String::Number(received) + " bytes)");
|
||||
return false;
|
||||
}
|
||||
|
||||
packet->Resize(received);
|
||||
packet->SetNetCode(netCode);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool UdpSocket::Send(const IpAddress& to, const void* buffer, std::size_t size, std::size_t* sent)
|
||||
{
|
||||
NazaraAssert(to.IsValid(), "Invalid ip address");
|
||||
@@ -77,6 +115,20 @@ namespace Nz
|
||||
return true;
|
||||
}
|
||||
|
||||
bool UdpSocket::SendPacket(const IpAddress& to, const NetPacket& packet)
|
||||
{
|
||||
std::size_t size = 0;
|
||||
const UInt8* ptr = static_cast<const UInt8*>(packet.OnSend(&size));
|
||||
if (!ptr)
|
||||
{
|
||||
m_lastError = SocketError_Packet;
|
||||
NazaraError("Failed to prepare packet");
|
||||
return false;
|
||||
}
|
||||
|
||||
return Send(to, ptr, size, nullptr);
|
||||
}
|
||||
|
||||
void UdpSocket::OnClose()
|
||||
{
|
||||
AbstractSocket::OnClose();
|
||||
|
||||
Reference in New Issue
Block a user