WIP Clients are working properly, servers are not.

This commit is contained in:
Jocke
2016-02-09 11:43:16 +01:00
parent ba9419b342
commit fccd8c64e7
19 changed files with 277 additions and 166 deletions
+7 -4
View File
@@ -13,6 +13,8 @@
#include "Network/Network.h" #include "Network/Network.h"
#include "Network/MessageType.h" #include "Network/MessageType.h"
#include "Network/PlayerDefinition.h" #include "Network/PlayerDefinition.h"
#include "Network/UDPClient.h"
#include "Network/TCPClient.h"
#include "Network/SnapshotDefinitions.h" #include "Network/SnapshotDefinitions.h"
#include "Core/World.h" #include "Core/World.h"
#include "Core/EventBroker.h" #include "Core/EventBroker.h"
@@ -35,7 +37,6 @@ protected:
int port = 0; int port = 0;
// Sending message to server logic // Sending message to server logic
int bytesRead = -1; int bytesRead = -1;
char readBuffer[BUFFERSIZE] = { 0 };
// Packet loss logic // Packet loss logic
PacketID m_PacketID = 0; PacketID m_PacketID = 0;
@@ -66,9 +67,6 @@ protected:
std::vector<Events::InputCommand> m_InputCommandBuffer; std::vector<Events::InputCommand> m_InputCommandBuffer;
// Private member functions // Private member functions
virtual void send(Packet& packet) = 0;
virtual void readFromServer() = 0;
virtual void connect() = 0;
void disconnect(); void disconnect();
void parseMessageType(Packet& packet); void parseMessageType(Packet& packet);
void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType); void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType);
@@ -103,6 +101,11 @@ protected:
bool OnPlayerDamage(const Events::PlayerDamage& e); bool OnPlayerDamage(const Events::PlayerDamage& e);
EventRelay<Client, Events::PlayerSpawned> m_EPlayerSpawned; EventRelay<Client, Events::PlayerSpawned> m_EPlayerSpawned;
bool OnPlayerSpawned(const Events::PlayerSpawned& e); bool OnPlayerSpawned(const Events::PlayerSpawned& e);
private:
//UDPClient m_UDPClient;
//TCPClient m_TCPClient;
TCPClient m_UDPClient;
}; };
#endif #endif
+2 -1
View File
@@ -18,7 +18,8 @@ enum class MessageType
OnPlayerSpawned, OnPlayerSpawned,
EntityDeleted, EntityDeleted,
ComponentDeleted, ComponentDeleted,
PlayerTransform PlayerTransform,
Invalid
}; };
#endif #endif
+2
View File
@@ -30,6 +30,8 @@ protected:
std::clock_t m_SaveDataTimer; std::clock_t m_SaveDataTimer;
unsigned int m_MaxConnections; unsigned int m_MaxConnections;
unsigned int m_TimeoutMs; unsigned int m_TimeoutMs;
void logSentData(int bytesSent);
void logReceivedData(int bytesReceived);
void saveToFile(); void saveToFile();
void updateNetworkData(); void updateNetworkData();
void initialize(); void initialize();
+21
View File
@@ -0,0 +1,21 @@
#ifndef NetworkClient_h__
#define NetworkClient_h__
#include "Network/Packet.h"
#define BUFFERSIZE 32000
typedef unsigned int PlayerID;
typedef unsigned int PacketID;
class NetworkClient
{
public:
virtual void Connect(std::string playerName, std::string address, int port) = 0;
virtual void Disconnect() = 0;
virtual void Receive(Packet& packet) = 0;
virtual void Send(Packet & packet) = 0;
virtual bool IsSocketAvailable() = 0;
protected:
char m_ReadBuffer[BUFFERSIZE] = { 0 };
};
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef NetworkServer_h__
#define NetworkServer_h__
#include "Network/Packet.h"
#define BUFFERSIZE 32000
typedef unsigned int PlayerID;
typedef unsigned int PacketID;
class NetworkServer
{
//public:
// virtual void Connect(std::string playerName, std::string address, int port) = 0;
// virtual void Disconnect() = 0;
// virtual Packet Receive() = 0;
// virtual void Send(Packet & packet) = 0;
//protected:
// char m_ReadBuffer[BUFFERSIZE] = { 0 };
};
#endif
+5
View File
@@ -49,12 +49,15 @@ public:
void WriteData(char* data, int sizeOfData); void WriteData(char* data, int sizeOfData);
// Pops the first element as if it was a string. // Pops the first element as if it was a string.
std::string ReadString(); std::string ReadString();
// Construct a packet
void ReconstructFromData(char* data, int SizeOfData);
// Update size of packet variable in header // Update size of packet variable in header
void UpdateSize(); void UpdateSize();
char* ReadData(int SizeOfData); char* ReadData(int SizeOfData);
void ChangePacketID(unsigned int& packetID); void ChangePacketID(unsigned int& packetID);
int Size() { return m_Offset; }; int Size() { return m_Offset; };
char* Data() { return m_Data; }; char* Data() { return m_Data; };
MessageType GetMessageType() { return m_MessageType; };
unsigned int DataReadSize() { return m_ReturnDataOffset; } unsigned int DataReadSize() { return m_ReturnDataOffset; }
unsigned int MaxSize() { return m_MaxPacketSize; } unsigned int MaxSize() { return m_MaxPacketSize; }
unsigned int HeaderSize() { return m_HeaderSize; } unsigned int HeaderSize() { return m_HeaderSize; }
@@ -65,7 +68,9 @@ private:
int m_Offset = 0; int m_Offset = 0;
unsigned int m_MaxPacketSize = 512; unsigned int m_MaxPacketSize = 512;
unsigned int m_HeaderSize = 0; unsigned int m_HeaderSize = 0;
MessageType m_MessageType = MessageType::Invalid;
void resizeData(); void resizeData();
void resizeData(int size);
}; };
#endif #endif
+17 -8
View File
@@ -1,23 +1,32 @@
#ifndef TCPClient_h__ #ifndef TCPClient_h__
#define TCPClient_h__ #define TCPClient_h__
#include "Client.h" #include <boost/asio.hpp>
#include "NetworkClient.h"
class TCPClient : public Client class TCPClient : public NetworkClient
{ {
public: public:
TCPClient(ConfigFile* config); TCPClient();
~TCPClient(); ~TCPClient();
void Connect(std::string playerName, std::string address, int port);
void Disconnect();
void Receive(Packet& packet);
void Send(Packet & packet);
bool IsSocketAvailable();
private: private:
// Assio UDP logic
//boost::asio::io_service m_IOService;
//boost::asio::ip::udp::endpoint m_ReceiverEndpoint;
//boost::shared_ptr<boost::asio::ip::udp::socket> m_Socket;
// Assio TCP logic // Assio TCP logic
boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::ip::tcp::endpoint m_Endpoint;
boost::asio::io_service m_IOService; boost::asio::io_service m_IOService;
std::unique_ptr<boost::asio::ip::tcp::socket> m_Socket; std::unique_ptr<boost::asio::ip::tcp::socket> m_Socket;
int readBuffer(char* data);
void connect(); PacketID m_SendPacketID = 0;
void readFromServer(); bool m_IsConnected = false;
int receive(char * data);
void send(Packet & packet);
}; };
#endif #endif
+17 -10
View File
@@ -1,24 +1,31 @@
#ifndef UDPClient_h__ #ifndef UDPClient_h__
#define UDPClient_h__ #define UDPClient_h__
#include "Client.h" #include <boost/asio.hpp>
#include "Network/NetworkClient.h"
//virtual void Connect(std::string address, int port) = 0;
//virtual int Receive(char * data) = 0;
//virtual void Send(Packet & packet) = 0;
//virtual void Disconnect() = 0;
class UDPClient : public NetworkClient
class UDPClient : public Client
{ {
public: public:
UDPClient(ConfigFile* config); UDPClient();
~UDPClient(); ~UDPClient();
void Connect(std::string playerName, std::string address, int port);
void Disconnect();
void Receive(Packet& packet);
void Send(Packet & packet);
bool IsSocketAvailable();
private: private:
// Assio UDP logic // Assio UDP logic
boost::asio::io_service m_IOService; boost::asio::io_service m_IOService;
boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::ip::udp::endpoint m_ReceiverEndpoint;
boost::asio::ip::udp::socket m_Socket; boost::shared_ptr<boost::asio::ip::udp::socket> m_Socket;
int readBuffer(char* data);
void connect(); PacketID m_SendPacketID = 0;
void readFromServer();
int receive(char * data);
void send(Packet & packet);
}; };
#endif #endif
+4
View File
@@ -26,6 +26,8 @@
// Network // Network
#include <boost/thread.hpp> #include <boost/thread.hpp>
#include "Network/Network.h" #include "Network/Network.h"
// Client
#include "Network/Client.h"
// Hybrid // Hybrid
#include "Network/HybridServer.h" #include "Network/HybridServer.h"
#include "Network/HybridClient.h" #include "Network/HybridClient.h"
@@ -68,7 +70,9 @@ private:
// Network methods // Network methods
void networkFunction(); void networkFunction();
Network* m_ClientOrServer; Network* m_ClientOrServer;
std::unique_ptr<Client> m_Client;
bool m_IsClientOrServer = false; bool m_IsClientOrServer = false;
bool m_IsServer = false;
// Sound // Sound
SoundSystem* m_SoundSystem; SoundSystem* m_SoundSystem;
+19 -14
View File
@@ -17,8 +17,7 @@ Client::Client(ConfigFile* config)
} }
Client::~Client() Client::~Client()
{ { }
}
void Client::Start(World* world, EventBroker* eventBroker) void Client::Start(World* world, EventBroker* eventBroker)
{ {
@@ -35,17 +34,23 @@ void Client::Start(World* world, EventBroker* eventBroker)
void Client::Update() void Client::Update()
{ {
m_EventBroker->Process<Client>(); m_EventBroker->Process<Client>();
readFromServer(); while (m_UDPClient.IsSocketAvailable()) {
// Packet will get real data in receive
Packet packet(MessageType::Invalid);
m_UDPClient.Receive(packet);
parseMessageType(packet);
}
if (m_IsConnected) { if (m_IsConnected) {
hasServerTimedOut(); hasServerTimedOut();
// Don't sent 1 input in 1 packet, bunch em up. // Don't send 1 input in 1 packet, bunch em up.
if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) {
sendInputCommands(); sendInputCommands();
m_TimeSinceSentInputs = std::clock(); m_TimeSinceSentInputs = std::clock();
} }
sendLocalPlayerTransform(); sendLocalPlayerTransform();
} }
Network::Update(); //Network::Update();
} }
void Client::parseMessageType(Packet& packet) void Client::parseMessageType(Packet& packet)
@@ -59,7 +64,7 @@ void Client::parseMessageType(Packet& packet)
// Read packet ID // Read packet ID
m_PreviousPacketID = m_PacketID; // Set previous packet id m_PreviousPacketID = m_PacketID; // Set previous packet id
m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
identifyPacketLoss(); //identifyPacketLoss();
switch (static_cast<MessageType>(messageType)) { switch (static_cast<MessageType>(messageType)) {
case MessageType::Connect: case MessageType::Connect:
@@ -118,7 +123,7 @@ void Client::parsePing()
Packet packet(MessageType::Ping, m_SendPacketID); Packet packet(MessageType::Ping, m_SendPacketID);
packet.WriteString("Ping recieved"); packet.WriteString("Ping recieved");
send(packet); m_UDPClient.Send(packet);
} }
void Client::parseKick() void Client::parseKick()
@@ -250,14 +255,14 @@ void Client::disconnect()
m_PreviousPacketID = 0; m_PreviousPacketID = 0;
m_PacketID = 0; m_PacketID = 0;
Packet packet(MessageType::Disconnect, m_SendPacketID); Packet packet(MessageType::Disconnect, m_SendPacketID);
send(packet); m_UDPClient.Send(packet);
} }
bool Client::OnInputCommand(const Events::InputCommand & e) bool Client::OnInputCommand(const Events::InputCommand & e)
{ {
if (e.Command == "ConnectToServer") { // Connect for now if (e.Command == "ConnectToServer") { // Connect for now
if (e.Value > 0) { if (e.Value > 0) {
connect(); m_UDPClient.Connect(m_PlayerName, address, port);
} }
//LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID);
return true; return true;
@@ -280,7 +285,7 @@ bool Client::OnInputCommand(const Events::InputCommand & e)
m_SaveDataTimer = std::clock(); m_SaveDataTimer = std::clock();
} }
} else { } else {
if (m_IsConnected) { if (m_IsConnected) {
m_InputCommandBuffer.push_back(e); m_InputCommandBuffer.push_back(e);
} }
//LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID);
@@ -294,7 +299,7 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e)
Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); Packet packet(MessageType::OnPlayerDamage, m_SendPacketID);
packet.WritePrimitive(e.Damage); packet.WritePrimitive(e.Damage);
packet.WritePrimitive(m_ClientIDToServerID.at(e.Player.ID)); packet.WritePrimitive(m_ClientIDToServerID.at(e.Player.ID));
send(packet); m_UDPClient.Send(packet);
return false; return false;
} }
@@ -322,7 +327,7 @@ void Client::sendLocalPlayerTransform()
packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.x);
packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.y);
packet.WritePrimitive(orientation.z); packet.WritePrimitive(orientation.z);
send(packet); m_UDPClient.Send(packet);
} }
void Client::identifyPacketLoss() void Client::identifyPacketLoss()
@@ -365,7 +370,7 @@ void Client::sendInputCommands()
packet.WriteString(m_InputCommandBuffer[i].Command); packet.WriteString(m_InputCommandBuffer[i].Command);
packet.WritePrimitive(m_InputCommandBuffer[i].Value); packet.WritePrimitive(m_InputCommandBuffer[i].Value);
} }
send(packet); m_UDPClient.Send(packet);
m_InputCommandBuffer.clear(); m_InputCommandBuffer.clear();
} }
} }
@@ -373,7 +378,7 @@ void Client::sendInputCommands()
void Client::becomePlayer() void Client::becomePlayer()
{ {
Packet packet = Packet(MessageType::BecomePlayer, m_SendPacketID); Packet packet = Packet(MessageType::BecomePlayer, m_SendPacketID);
send(packet); m_UDPClient.Send(packet);
} }
bool Client::clientServerMapsHasEntity(EntityID clientEntityID) bool Client::clientServerMapsHasEntity(EntityID clientEntityID)
+15
View File
@@ -5,6 +5,21 @@ void Network::Update()
updateNetworkData(); updateNetworkData();
} }
void Network::logSentData(int bytesSent)
{
}
void Network::logReceivedData(int bytesReceived)
{
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataReceived += bytesReceived;
m_NetworkData.DataReceivedThisInterval += bytesReceived;
m_NetworkData.AmountOfMessagesReceived++;
}
}
void Network::saveToFile() void Network::saveToFile()
{ {
std::ofstream outfile; std::ofstream outfile;
+32 -9
View File
@@ -37,6 +37,7 @@ void Packet::Init(MessageType type, unsigned int & packetID)
// allocate memory for size of packet(only used in tcp) // allocate memory for size of packet(only used in tcp)
Packet::WritePrimitive<int>(0); Packet::WritePrimitive<int>(0);
// Add message type // Add message type
m_MessageType = type;
int messageType = static_cast<int>(type); int messageType = static_cast<int>(type);
Packet::WritePrimitive<int>(messageType); Packet::WritePrimitive<int>(messageType);
Packet::WritePrimitive<int>(packetID); Packet::WritePrimitive<int>(packetID);
@@ -58,9 +59,12 @@ void Packet::WriteString(const std::string& str)
void Packet::WriteData(char * data, int sizeOfData) void Packet::WriteData(char * data, int sizeOfData)
{ {
if (m_Offset + sizeOfData > m_MaxPacketSize) { if (m_Offset + sizeOfData > m_MaxPacketSize) {
//LOG_WARNING("Packet::WriteData(): Data size in packet exceeded maximum packet size. New size is %i bytes\n", m_MaxPacketSize*2); //LOG_WARNING("Packet::WriteData(): Data size in packet exceeded maximum packet size. New size is %i bytes\n", m_MaxPacketSize*2);
resizeData(); while (m_Offset + sizeOfData > m_MaxPacketSize) {
resizeData();
}
} }
memcpy(m_Data + m_Offset, data, sizeOfData); memcpy(m_Data + m_Offset, data, sizeOfData);
m_Offset += sizeOfData; m_Offset += sizeOfData;
@@ -78,19 +82,34 @@ std::string Packet::ReadString()
return returnValue; return returnValue;
} }
void Packet::ReconstructFromData(char * data, int sizeOfData)
{
if (sizeOfData > m_MaxPacketSize) {
// Delete our data
delete[] m_Data;
// Set new max size
m_MaxPacketSize = sizeOfData;
m_Data = new char[m_MaxPacketSize];
// while we resized the old data container.
}
memcpy(m_Data, data, sizeOfData);
m_Offset = sizeOfData;
}
void Packet::UpdateSize() void Packet::UpdateSize()
{ {
memcpy(m_Data, &m_Offset, sizeof(int)); memcpy(m_Data, &m_Offset, sizeof(int));
} }
char * Packet::ReadData(int SizeOfData) char * Packet::ReadData(int sizeOfData)
{ {
if (m_Offset < m_ReturnDataOffset + SizeOfData) { if (m_Offset < m_ReturnDataOffset + sizeOfData) {
//LOG_WARNING("packet ReadData(): Oh no! You are trying to remove things outside my memory kingdom"); //LOG_WARNING("packet ReadData(): Oh no! You are trying to remove things outside my memory kingdom");
return nullptr; return nullptr;
} }
unsigned int oldReturnDataOffset = m_ReturnDataOffset; unsigned int oldReturnDataOffset = m_ReturnDataOffset;
m_ReturnDataOffset += SizeOfData; m_ReturnDataOffset += sizeOfData;
return (m_Data + oldReturnDataOffset); return (m_Data + oldReturnDataOffset);
} }
@@ -103,20 +122,24 @@ void Packet::ChangePacketID(unsigned int & packetID)
void Packet::resizeData() void Packet::resizeData()
{ {
resizeData(m_MaxPacketSize * 2);
}
void Packet::resizeData(int size)
{
// Allocate memory to store our data in // Allocate memory to store our data in
char* holdData = new char[m_MaxPacketSize]; char* holdData = new char[m_MaxPacketSize];
// Copy our data to the newly allocated memory // Copy our data to the newly allocated memory
memcpy(holdData, m_Data, m_Offset); memcpy(holdData, m_Data, m_Offset);
// Increase max packet size // Increase max packet size
m_MaxPacketSize = m_MaxPacketSize * 2; m_MaxPacketSize = size;
// Delete our data // Delete our data
delete m_Data; delete[] m_Data;
// Allocate twice the memory we had before // Allocate memory
m_Data = new char[m_MaxPacketSize]; m_Data = new char[m_MaxPacketSize];
// Copy our data to new location // Copy our data to new location
memcpy(m_Data, holdData, m_Offset); memcpy(m_Data, holdData, m_Offset);
// Delete the memory allocated to hold our data // Delete the memory allocated to hold our data
// while we resized the old data container. // while we resized the old data container.
delete holdData; delete[] holdData;
} }
+18 -3
View File
@@ -8,8 +8,7 @@ Server::Server()
pingIntervalMs = config->Get<float>("Networking.PingIntervalMs", 1000); pingIntervalMs = config->Get<float>("Networking.PingIntervalMs", 1000);
} }
Server::~Server() Server::~Server()
{ { }
}
void Server::Start(World* world, EventBroker* eventBroker) void Server::Start(World* world, EventBroker* eventBroker)
{ {
m_World = world; m_World = world;
@@ -25,11 +24,27 @@ void Server::Start(World* world, EventBroker* eventBroker)
void Server::Update() void Server::Update()
{ {
readFromClients(); readFromClients();
std::clock_t currentTime = std::clock();
// Send snapshot
if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) {
sendSnapshot();
previousSnapshotMessage = currentTime;
}
// Send pings each
if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) {
sendPing();
previousePingMessage = currentTime;
}
// Time out logic
if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) {
checkForTimeOuts();
timOutTimer = currentTime;
}
m_EventBroker->Process<Server>(); m_EventBroker->Process<Server>();
if (isReadingData) { if (isReadingData) {
Network::Update(); Network::Update();
} }
} }
void Server::parseMessageType(Packet& packet) void Server::parseMessageType(Packet& packet)
+36 -30
View File
@@ -2,46 +2,55 @@
using namespace boost::asio::ip; using namespace boost::asio::ip;
TCPClient::TCPClient(ConfigFile * config) : Client(config) TCPClient::TCPClient()
{ {
m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port);
m_Socket = std::unique_ptr<tcp::socket>(new tcp::socket(m_IOService, m_Endpoint));
tcp::no_delay option(true);
m_Socket->set_option(option);
} }
TCPClient::~TCPClient() TCPClient::~TCPClient()
{ {
} }
void TCPClient::connect() void TCPClient::Connect(std::string playerName, std::string address, int port)
{ {
if (m_Socket) {
return;
}
if (!m_IsConnected) { if (!m_IsConnected) {
boost::system::error_code error = boost::asio::error::host_not_found; boost::system::error_code error = boost::asio::error::host_not_found;
m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port);
m_Socket = std::unique_ptr<tcp::socket>(new tcp::socket(m_IOService, m_Endpoint));
tcp::no_delay option(true);
m_Socket->set_option(option);
m_Socket->close(); m_Socket->close();
m_Socket->connect(m_Endpoint, error); m_Socket->connect(m_Endpoint, error);
LOG_INFO(error.message().c_str()); LOG_INFO(error.message().c_str());
if (!error) { if (!error) {
m_IsConnected = true;
Packet packet(MessageType::Connect, m_SendPacketID); Packet packet(MessageType::Connect, m_SendPacketID);
packet.WriteString(m_PlayerName); packet.WriteString(playerName);
m_StartPingTime = std::clock(); Send(packet);
send(packet);
} }
} }
} }
void TCPClient::readFromServer() void TCPClient::Disconnect()
{
}
void TCPClient::Receive(Packet& packet)
{ {
while (m_Socket->available()) { int bytesRead = readBuffer(m_ReadBuffer);
bytesRead = receive(readBuffer); if (bytesRead > 0) {
Packet packet(readBuffer, bytesRead); packet.ReconstructFromData(m_ReadBuffer, bytesRead);
parseMessageType(packet);
} }
} }
int TCPClient::receive(char * data) int TCPClient::readBuffer(char* data)
{ {
if (!m_Socket) {
return 0;
}
boost::system::error_code error; boost::system::error_code error;
// Read size of packet // Read size of packet
int bytesReceived = m_Socket->read_some(boost int bytesReceived = m_Socket->read_some(boost
@@ -54,29 +63,26 @@ int TCPClient::receive(char * data)
bytesReceived += m_Socket->read_some(boost bytesReceived += m_Socket->read_some(boost
::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived),
error); error);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataReceived += bytesReceived;
m_NetworkData.DataReceivedThisInterval += bytesReceived;
m_NetworkData.AmountOfMessagesReceived++;
}
if (error) { if (error) {
//LOG_ERROR("receive: %s", error.message().c_str()); //LOG_ERROR("receive: %s", error.message().c_str());
} }
return bytesReceived; return bytesReceived;
} }
void TCPClient::send(Packet & packet) void TCPClient::Send(Packet & packet)
{ {
packet.UpdateSize(); packet.UpdateSize();
boost::system::error_code error; boost::system::error_code error;
m_Socket->send(boost::asio::buffer( m_Socket->send(boost::asio::buffer(
packet.Data(), packet.Data(),
packet.Size()), 0, error); packet.Size()), 0, error);
// Network Debug data //Network::logSentData(packet.Size());
if (isReadingData) {
m_NetworkData.TotalDataSent += packet.Size();
m_NetworkData.DataSentThisInterval += packet.Size();
m_NetworkData.AmountOfMessagesSent++;
}
} }
bool TCPClient::IsSocketAvailable()
{
if (!m_Socket) {
return false;
}
return m_Socket->available();
}
+2 -22
View File
@@ -7,8 +7,7 @@ TCPServer::TCPServer()
} }
TCPServer::~TCPServer() TCPServer::~TCPServer()
{ { }
}
void TCPServer::readFromClients() void TCPServer::readFromClients()
{ {
@@ -30,25 +29,6 @@ void TCPServer::readFromClients()
} }
} }
} }
std::clock_t currentTime = std::clock();
// Send snapshot
if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) {
sendSnapshot();
previousSnapshotMessage = currentTime;
}
// Send pings each
if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) {
sendPing();
previousePingMessage = currentTime;
}
// Time out logic
if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) {
checkForTimeOuts();
timOutTimer = currentTime;
}
} }
void TCPServer::acceptNewConnections() void TCPServer::acceptNewConnections()
@@ -80,7 +60,7 @@ void TCPServer::parseConnect(Packet & packet)
LOG_INFO("Parsing connections"); LOG_INFO("Parsing connections");
// Check if player is already connected // Check if player is already connected
PlayerID playerID = GetPlayerIDFromEndpoint(); PlayerID playerID = GetPlayerIDFromEndpoint();
if(playerID = -1){ if (playerID = -1) {
return; return;
} }
+38 -34
View File
@@ -2,65 +2,69 @@
using namespace boost::asio::ip; using namespace boost::asio::ip;
UDPClient::UDPClient(ConfigFile * config) : Client(config), m_Socket(m_IOService) UDPClient::UDPClient()
{ {
m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port);
m_Socket.connect(m_ReceiverEndpoint);
} }
UDPClient::~UDPClient() UDPClient::~UDPClient()
{ {
} }
void UDPClient::readFromServer() void UDPClient::Connect(std::string playerName, std::string address, int port)
{ {
while (m_Socket.available()) { if (m_Socket) {
bytesRead = receive(readBuffer); return;
if (bytesRead > 0) { }
Packet packet(readBuffer, bytesRead); m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port);
parseMessageType(packet); m_Socket = boost::shared_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService));
} m_Socket->connect(m_ReceiverEndpoint);
Packet packet(MessageType::Connect, m_SendPacketID);
packet.WriteString(playerName);
Send(packet);
}
void UDPClient::Disconnect()
{
}
void UDPClient::Receive(Packet& packet)
{
int bytesRead = readBuffer(m_ReadBuffer);
if (bytesRead > 0) {
packet.ReconstructFromData(m_ReadBuffer, bytesRead);
} }
} }
int UDPClient::receive(char* data) int UDPClient::readBuffer(char* data)
{ {
if (!m_Socket) {
return 0;
}
boost::system::error_code error; boost::system::error_code error;
int bytesReceived = m_Socket->receive_from(boost
int bytesReceived = m_Socket.receive_from(boost
::asio::buffer((void*)data, BUFFERSIZE), ::asio::buffer((void*)data, BUFFERSIZE),
m_ReceiverEndpoint, m_ReceiverEndpoint,
0, error); 0, error);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataReceived += bytesReceived;
m_NetworkData.DataReceivedThisInterval += bytesReceived;
m_NetworkData.AmountOfMessagesReceived++;
}
if (error) { if (error) {
//LOG_ERROR("receive: %s", error.message().c_str()); //LOG_ERROR("receive: %s", error.message().c_str());
} }
return bytesReceived; return bytesReceived;
} }
void UDPClient::send(Packet& packet) void UDPClient::Send(Packet& packet)
{ {
m_Socket.send_to(boost::asio::buffer( m_Socket->send_to(boost::asio::buffer(
packet.Data(), packet.Data(),
packet.Size()), packet.Size()),
m_ReceiverEndpoint, 0); m_ReceiverEndpoint, 0);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataSent += packet.Size();
m_NetworkData.DataSentThisInterval += packet.Size();
m_NetworkData.AmountOfMessagesSent++;
}
} }
void UDPClient::connect() bool UDPClient::IsSocketAvailable()
{ {
Packet packet(MessageType::Connect, m_SendPacketID); if (!m_Socket) {
packet.WriteString(m_PlayerName); return false;
m_StartPingTime = std::clock(); }
send(packet); return m_Socket->available();
} }
+1 -20
View File
@@ -6,8 +6,7 @@ UDPServer::UDPServer()
} }
UDPServer::~UDPServer() UDPServer::~UDPServer()
{ { }
}
void UDPServer::readFromClients() void UDPServer::readFromClients()
{ {
@@ -22,24 +21,6 @@ void UDPServer::readFromClients()
//LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what());
} }
} }
std::clock_t currentTime = std::clock();
// Send snapshot
if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) {
sendSnapshot();
previousSnapshotMessage = currentTime;
}
// Send pings each
if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) {
sendPing();
previousePingMessage = currentTime;
}
// Time out logic
if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) {
checkForTimeOuts();
timOutTimer = currentTime;
}
} }
void UDPServer::parseConnect(Packet& packet) void UDPServer::parseConnect(Packet& packet)
+21 -11
View File
@@ -43,7 +43,7 @@ Game::Game(int argc, char* argv[])
0, 0,
m_Config->Get<int>("Video.Width", 1280), m_Config->Get<int>("Video.Width", 1280),
m_Config->Get<int>("Video.Height", 720) m_Config->Get<int>("Video.Height", 720)
)); ));
m_Renderer->Initialize(); m_Renderer->Initialize();
//m_Renderer->Camera()->SetFOV(glm::radians(m_Config->Get<float>("Video.FOV", 90.f))); //m_Renderer->Camera()->SetFOV(glm::radians(m_Config->Get<float>("Video.FOV", 90.f)));
m_RenderFrame = new RenderFrame(); m_RenderFrame = new RenderFrame();
@@ -155,7 +155,11 @@ void Game::Tick()
// Update network // Update network
if (m_IsClientOrServer) { if (m_IsClientOrServer) {
m_ClientOrServer->Update(); if (m_IsServer)
m_ClientOrServer->Update();
else if (!m_IsServer) {
m_Client->Update();
}
} }
// Iterate through systems and update world! // Iterate through systems and update world!
m_EventBroker->Process<SystemPipeline>(); m_EventBroker->Process<SystemPipeline>();
@@ -178,19 +182,25 @@ void Game::debugTick(double dt)
void Game::networkFunction() void Game::networkFunction()
{ {
bool isServer = m_Config->Get<bool>("Networking.IsServer", false); m_IsServer = m_Config->Get<bool>("Networking.IsServer", false);
if (!isServer) { if (!m_IsServer) {
m_IsClientOrServer = true; m_IsClientOrServer = true;
m_ClientOrServer = new UDPClient(m_Config); m_Client = std::unique_ptr<Client>(new Client(m_Config));
//m_ClientOrServer = new TCPClient(m_Config); m_Client->Start(m_World, m_EventBroker);
//m_ClientOrServer = new HybridClient(m_Config);
} }
if (isServer) { //if (!isServer) {
// m_IsClientOrServer = true;
// m_ClientOrServer = new UDPClient(m_Config);
// //m_ClientOrServer = new TCPClient(m_Config);
// //m_ClientOrServer = new HybridClient(m_Config);
//}
if (m_IsServer) {
m_IsClientOrServer = true; m_IsClientOrServer = true;
m_ClientOrServer = new UDPServer(); // m_ClientOrServer = new UDPServer();
// m_ClientOrServer = new TCPServer(); m_ClientOrServer = new TCPServer();
//m_ClientOrServer = new HybridServer(); //m_ClientOrServer = new HybridServer();
m_ClientOrServer->Start(m_World, m_EventBroker);
} }
m_ClientOrServer->Start(m_World, m_EventBroker);
} }