Started work on networked test for ecs

This commit is contained in:
2019-06-28 03:18:54 +02:00
parent e43dbea6b1
commit f77c9d7823
4 changed files with 168 additions and 4 deletions

View File

@@ -0,0 +1,94 @@
#include <iostream>
#include <thread>
#include <functional>
#include <netinet/in.h>
#include "ecs-serial.h"
#include "ecs_network_components.h"
ecs::Manager manager;
void on_connect(int sock, sockaddr_in from) {
uint32_t ip = from.sin_addr.s_addr;
uint32_t bytes[4];
bytes[0] = ip & 0xff;
bytes[1] = (ip >> 8) & 0xff;
bytes[2] = (ip >> 16) & 0xff;
bytes[3] = (ip >> 24) & 0xff;
std::cout << "Client connected: " << bytes[0] << '.' << bytes[1] << '.' << bytes[2] << '.' << bytes[3] << '\n';
uint8_t buffer[1024];
buffer[0] = 'a';
if (sendto(sock, buffer, 1024, 0, (sockaddr*)&from, sizeof(from)) < 0) {
throw std::runtime_error("Failed to send ack to client");
}
// Send ids and all entities
// @todo We need to somehow write to the socket
// @todo Make everything thread safe
ecs::serial::serialize_ids(std::cout);
}
// For now we will just send the entire state every tick
void on_update() {
// Depending on the update type send it to all clients
// New component added -> send new id
// Component updated -> send updated component
}
void listener(int sock) {
// @todo Replace true with an atomic
while (true) {
int8_t buffer[1024];
// Wait on initial connection
sockaddr_in from;
socklen_t from_size = sizeof(from);
int bytes_received = recvfrom(sock, buffer, 1024, 0, (sockaddr*)&from, &from_size);
if (bytes_received < 0) {
throw std::runtime_error("Failed to receive data!");
}
switch (buffer[0]) {
case 'c':
on_connect(sock, from);
break;
}
}
}
int main() {
generated::init();
int address_family = AF_INET;
int type = SOCK_DGRAM;
int protocol = 0;
int sock = socket(address_family, type, protocol);
if (sock < 0) {
throw std::runtime_error("Failed to create socket!");
}
sockaddr_in local_address;
local_address.sin_family = AF_INET;
local_address.sin_port = htons(9999);
local_address.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (sockaddr*)&local_address, sizeof(local_address)) < 0) {
throw std::runtime_error("Failed to bind to port!");
}
std::thread lthread(std::bind(listener, sock));
std::cout << "Server started!\n";
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
lthread.join();
}