bettola/srv/main.cpp
Ritchie Cunningham 6e935918a3 feat(server) Added client/server for online play
Note: This is fucking broken! it's too early in the morning. Fix
tomorrow.
2025-09-13 05:22:30 +01:00

65 lines
1.9 KiB
C++

#include <cstdio>
#include "bettola/network/socket.h"
#include "bettola/network/net_common.h"
int main(void) {
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);
/* Main server loop. */
while(true) {
BettolaLib::Network::Socket* client_socket = server_socket.accept();
if(client_socket == nullptr) {
printf("Bettola Server: Failed to accept client connection.\n");
continue; /* try accepting again. */
}
printf("Bettola Server: Client connected!\n");
char buffer[256]; /* Small buffer for echo. */
ssize_t bytes_received;
do {
bytes_received = client_socket->recv(buffer, sizeof(buffer) - 1);
if(bytes_received > 0) {
buffer[bytes_received] = '\n';
printf("Bettola Server: Received from client: '%s'\n", buffer);
client_socket->send(buffer, bytes_received); /* Echo back. */
} else if(bytes_received == -1) {
perror("Bettola Server: Error receiving from client.");
}
} while(bytes_received > 0);
/* Let's just keep it connected for now. */
// printf("Bettola Server: Client disconnected.\n");
// client_socket->close();
// delete client_socket;
}
server_socket.close(); /* Shouldn't reach here. */
printf("=== Bettola Server: Shutting Down ===\n");
return 0;
}