bettola/srv/main.cpp

92 lines
2.6 KiB
C++

#include <cstddef>
#include <cstdio>
#include <chrono>
#include <thread>
#include "bettola/network/socket.h"
#include "bettola/network/net_common.h"
#include "bettola/network/message.h"
#include "bettola/network/player_pos_message.h"
#include "game/game.h"
int main(void) {
Game game;
printf("=== Bettola Server: Starting ===\n");
BettolaLib::Network::Socket server_socket;
if(!server_socket.create()) {
printf("Bettola Server: Failed to create socket.\n");
return 1;
}
if(!server_socket.bind(BettolaLib::Network::DEFAULT_PORT)) {
printf("Bettola Server: Failed to bind socket to port %hu.\n",
BettolaLib::Network::DEFAULT_PORT);
server_socket.close();
return 1;
}
if(!server_socket.listen()) {
printf("Bettola Server: Failed to listen on socket.\n");
server_socket.close();
return 1;
}
printf("Bettola Server: Listening on port %hu...\n", BettolaLib::Network::DEFAULT_PORT);
auto last_time = std::chrono::high_resolution_clock::now();
/* Main server loop. */
while(true) {
auto current_time = std::chrono::high_resolution_clock::now();
auto delta_time = std::chrono::duration_cast<std::chrono::duration<double>>
(current_time-last_time).count();
/* TODO:
* Accept new connections.
* This is blocking.. Will fix later.
*/
BettolaLib::Network::Socket* client_socket = server_socket.accept();
if(client_socket != nullptr) {
Player* new_player = game.add_player(client_socket);
printf("Bettola Server: Client connected! Player ID: %u\n", new_player->get_id());
}
/* TODO:
* Process messages from clients.
* this is also blocking and only handles one client at a time. fix later
*/
if(client_socket != nullptr) {
while(true) {
BettolaLib::Network::MessageHeader header;
ssize_t bytes_received = client_socket->recv(&header, sizeof(header));
if(bytes_received <= 0) {
//game.remove_player(new_player->get_id());
break;
}
if(header.type == BettolaLib::Network::MessageType::PlayerPosition) {
BettolaLib::Network::PlayerPosMessage msg;
bytes_received = client_socket->recv(&msg, sizeof(msg));
if(bytes_received > 0) {
//game.update_player_pos(new_player->get_id(), msg.x, msg.y);
}
}
}
}
/* Broadcase game state. */
game.broadcast_game_state();
/* Sleep for a short time to avoid busy-waiting. */
std::this_thread::sleep_for(std::chrono::milliseconds(1000/60));
}
server_socket.close(); /* Shouldn't reach here. */
printf("=== Bettola Server: Shutting Down ===\n");
return 0;
}