mostly just refactoring socket stuff

This commit is contained in:
snit 2024-10-28 00:13:05 -05:00
parent 92fed87080
commit c892acab80
5 changed files with 25 additions and 15 deletions

View File

@ -2,9 +2,9 @@
A list of things I'd like to accomplish
## In Progress
* Split game ticking and socket connecting logic (can only tick on connection atm)
## Completed
* Split game ticking and socket connecting logic (can only tick on connection atm)
* Client send request
* Server handle request and send response
* Client handle response

View File

@ -12,9 +12,6 @@ struct game_data_t {
struct world_t world;
pthread_mutex_t world_lock;
int socket;
int socket_accept;
};
#endif

View File

@ -114,6 +114,9 @@ int main(int argc, char **argv) {
pthread_join(pthread_socket, (void **)&err); // No way this is correct lol
if (err) goto handle_error;
pthread_join(pthread_simulation, (void **)&err);
if (err) goto handle_error;
// Deinitialisation
pthread_mutex_destroy(&data.world_lock);

View File

@ -43,25 +43,31 @@ void socket_free(int const *sockptr) {
}
static enum error_t socket_handle(struct game_data_t *data) {
struct socket_data_t {
struct game_data_t *game_data;
int socket;
};
static enum error_t socket_handle(struct socket_data_t *data) {
enum error_t err = ERR_OK;
char output_buffer[8192] = { 0 };
char input_buffer[8192] = { 0 };
// Receive request from client
read(data->socket_accept, input_buffer, 8192);
read(data->socket, input_buffer, 8192);
struct request_t request = { 0 };
err = request_deserialise_str(&request, input_buffer);
if (err != ERR_OK) return err;
// Send response to client
struct response_t response = handle_request(&request, data);
struct response_t response = handle_request(&request, data->game_data);
err = response_serialise_buf(&response, output_buffer, 8192);
if (err != ERR_OK) return err;
write(data->socket_accept, output_buffer, 8192);
write(data->socket, output_buffer, 8192);
return ERR_OK;
}
@ -72,27 +78,30 @@ static enum error_t socket_thread_body(struct game_data_t *data) {
enum error_t err = ERR_OK;
if ((err = socket_init(&data->socket))) return err;
struct socket_data_t socket_data = { data, 0 };
int socket = 0;
if ((err = socket_init(&socket))) return err;
for (int sock_accept;;) {
if ((sock_accept = accept(data->socket, NULL, NULL)) < 0) {
if ((sock_accept = accept(socket, NULL, NULL)) < 0) {
err = ERR_SOCKET;
goto error_pre;
};
data->socket_accept = sock_accept;
if ((err = socket_handle(data))) goto error_pre;
socket_data.socket = sock_accept;
if ((err = socket_handle(&socket_data))) goto error_pre;
close(data->socket_accept);
close(socket_data.socket);
continue;
error_pre:
close(data->socket_accept);
close(socket_data.socket);
goto error;
}
error:
socket_free(&data->socket);
socket_free(&socket);
return err;
}

View File

@ -8,6 +8,7 @@
#define SOCKET_PATH "/tmp/swd.sock"
// Socket path should be a shared setting between server and client
enum error_t socket_init(int *);
void socket_free(int const *);