-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathASCIIlosaurus_server.c
More file actions
359 lines (321 loc) · 13.1 KB
/
ASCIIlosaurus_server.c
File metadata and controls
359 lines (321 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
* @file ASCIIlosaurus_server.c
* @brief Server portion of the UDP game - process commands and sends state to client
* @author Alejandro Alvarado
* @course Intro to Operating Systems - CS333-006
* @date March 11, 2026
*
* @details
* Note that large portions of this code are from the skeleton file provided by
* the instructor: R Jesse chaney (rchaney@pdx.edu)
*
* This file creates the server side of the UDP terminal game. The server is
* responsible for creating a UDP socket and binding it to a specified port,
* maintaining the world state, connecting players, and providing those updates
* to clients.
*/
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdbool.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <ncurses.h>
#include <signal.h>
#include <libgen.h>
#include <time.h>
#include "ASCIIlosaurus_world.h"
#define BUF_SIZE 100
#define SOCKET_FD 1
// #define POLL_TIMEOUT 500
#define POLL_TIMEOUT 300
#define DEFAULT_X 20
#define DEFAULT_Y 10
#define OPTIONS "P:vh"
volatile sig_atomic_t keep_running = 1; // this is how we terminate the server (end the inf loop)
static bool is_verbose = false;
static socklen_t addrlen = sizeof(struct sockaddr_in);
static world_state_t world; // this is what we will send to the client - it contains state like player pos
static struct sockaddr_in clients[MAX_PLAYERS]; // this is going to store the address of each connected client
static const char symbols[MAX_PLAYERS] = {
'@', '=', '$', '%', '^', '&', '*', 'X', '?', '+'}; // symbols represent playable characters or players
static void process_server_command(void);
static void handle_sigint(int);
static void update_clients(int);
int
main(int argc, char *argv[])
{
struct sockaddr_in servaddr; // this contains our connnection info
struct pollfd fds[2];
int port = DEFAULT_PORT;
int socketfd = -1; // this is our socket
// Process the command line if anything was passed
{
int opt = 0;
while ((opt = getopt(argc, argv, OPTIONS)) != -1) {
switch (opt) {
case 'P':
port = atoi(optarg);
break;
case 'v':
is_verbose = true;
break;
case 'h':
printf("Usage: ASCIIlosaurus_server [-P port] [-v] [-h]\n");
printf(" -P # Set server port (default: %d)\n", DEFAULT_PORT);
printf(" -v Enable verbose logging to stderr\n");
printf(" -h Print this help and exit\n");
exit(EXIT_SUCCESS);
break;
default:
break;
}
}
}
// initialize world
world.client_char = ' '; // placeholder until we have a connection
// setup the defualt positions of each player (spawn pos)
for (int i = 0; i < MAX_PLAYERS; ++i) {
world.players[i].x = 0;
world.players[i].y = 0;
world.players[i].symbol = symbols[i];
world.players[i].active = false;
world.players[i].cloaked = false; // this is not used
world.players[i].cloak_countdown = 0; // this is not used
}
memset(clients, 0, sizeof(clients)); // prepare mem area with clean null values
// register sig handler for ctrl-c
{
struct sigaction sa;
sa.sa_handler = handle_sigint;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
(void)sigaction(SIGINT, &sa, NULL);
(void)sigaction(SIGTERM, &sa, NULL);
}
// Create an IPv4 datagram socket
if ((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket creation error");
return EXIT_FAILURE;
}
fds[STDIN_FILENO].fd = STDIN_FILENO; // STDIN_FILENO == 0
fds[STDIN_FILENO].events = POLLIN; // this is for processing data from stdin ie the keyboard (read events)
fds[SOCKET_FD].fd = socketfd;
fds[SOCKET_FD].events = POLLIN; // read events from the client
memset(&servaddr, 0, sizeof(struct sockaddr_in)); // again prepare mem area with clean values
servaddr.sin_family = AF_INET; // IPv4 connection
servaddr.sin_port = htons((uint16_t)port); // little-endian -> big-endian
servaddr.sin_addr.s_addr = INADDR_ANY; // allow any connection
if (bind(socketfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) { // bind our datagram socket to the port
perror("bind failure");
fprintf(stderr, " Port %d must already be in use.\n", port);
fprintf(stderr, " Try another with the -P # command line option.\n");
fprintf(stderr, " Remember to start your client with the same port.\n");
close(socketfd);
return EXIT_FAILURE;
}
if (is_verbose) {
fprintf(stderr, "Server listening on port %d\n", port);
}
// the server console prompt
printf("server > ");
// =============== Main Server Loop ===============
while (keep_running) {
int ret = -1; // this will signal the program that something arrived from a client and/or stdin
int buf = -1;
ssize_t br = -1; // bytes read
struct sockaddr_in cliaddr; // connection info for clients - when they send something to us
// this is necessary
fflush(stdout);
ret = poll(fds, 2, POLL_TIMEOUT); // waits until fd is ready for I/O aka we can read from the socket now
if (ret == 0) {
// a timeout
// update to the clients.
update_clients(socketfd);
} else if (ret > 0) {
// got input from either or both of stdin or the socket
if (fds[STDIN_FILENO].revents & POLLIN) { // process stdin first in case we press q
// user entered command from keyboard
process_server_command();
}
if (fds[SOCKET_FD].revents & POLLIN) {
// something arrived from a client
buf = 0;
addrlen = sizeof(struct sockaddr_in);
br = recvfrom(socketfd, &buf, sizeof(int), 0,
(struct sockaddr *)&cliaddr, &addrlen); // read bytes into buf
if (br == (ssize_t)sizeof(int)) { // an event is of size int
int found_it = -1; // how we find the client that sent server a command
int first_empty = -1;
int ch = (int)ntohl((uint32_t)buf); // get the character - convert from big-endian -> little-endian
// update or insert client
// first, locate which client just sent us a command
// or insert a new client into the client list
for (int i = 0; i < MAX_PLAYERS; ++i) {
if (world.players[i].active) {
// check to see if the port and ip match
if (clients[i].sin_port == cliaddr.sin_port &&
clients[i].sin_addr.s_addr == cliaddr.sin_addr.s_addr) {
found_it = i;
break;
}
} else if (first_empty == -1) { // this means the first character is spawning in
// keep track of where to place a new client
first_empty = i;
}
}
if ((found_it == -1) && (first_empty != -1)) {
if (is_verbose) {
fprintf(stderr, "%d: new player found %d\n", __LINE__, first_empty);
}
clients[first_empty] = cliaddr;
// put a new player in slightly different positions in the world.
world.players[first_empty].x = DEFAULT_X + first_empty;
world.players[first_empty].y = DEFAULT_Y + first_empty;
world.players[first_empty].symbol = symbols[first_empty];
world.players[first_empty].active = true;
} else if (found_it > -1) {
// Support gaming, vim, and arrow keys with collapsing cases
switch (ch) {
case 'w':
case 'k':
case KEY_UP:
world.players[found_it].y--;
if (world.players[found_it].y < 0) {
world.players[found_it].y = GRID_H - 1;
}
break;
case 's':
case 'j':
case KEY_DOWN:
world.players[found_it].y++;
if (world.players[found_it].y >= GRID_H) {
world.players[found_it].y = 0;
}
break;
case 'a':
case 'h':
case KEY_LEFT:
world.players[found_it].x--;
if (world.players[found_it].x < 0) {
world.players[found_it].x = GRID_W - 1;
}
break;
case 'd':
case 'l':
case KEY_RIGHT:
world.players[found_it].x++;
if (world.players[found_it].x >= GRID_W) {
world.players[found_it].x = 0;
}
break;
case 'q':
// client is leaving the game
world.players[found_it].active = false;
if (is_verbose) {
fprintf(stderr, "Player %d quit\n", found_it);
}
break;
default:
// unrecognized command - ignore
break;
}
}
// update all the clients
update_clients(socketfd);
}
}
} else if (ret == -1) {
if (errno == EINTR) {
// let the signal handler change keep_running
} else {
perror("poll error");
}
}
}
printf("\n\nexiting...\n");
if (socketfd != -1) {
close(socketfd);
}
return EXIT_SUCCESS;
}
static void
process_server_command(void)
{
static char buf[BUF_SIZE] = {'\0'};
memset(buf, 0, BUF_SIZE);
(void)read(STDIN_FILENO, buf, BUF_SIZE);
switch (buf[0]) {
case 'q':
// change the keep_running variable
keep_running = 0;
break;
case 'h':
// extra credit
printf("commands:\n");
printf(" q: quit\n");
printf(" h: help\n");
printf(" k: client keyboard characters\n");
printf(" l: list client ports\n");
break;
case 'k':
// extra credit
printf("client character movement keys:\n");
printf(" w k <up arrow> : move up\n");
printf(" a h <left arrow>: move left\n");
printf(" s j <down arrow>: move down\n");
printf(" d l <right arrow>: move right\n");
break;
case 'l':
// extra credit
for (int i = 0; i < MAX_PLAYERS; i++) {
if (world.players[i].active) {
char ip_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &clients[i].sin_addr, ip_str, INET_ADDRSTRLEN); // binary to text
printf(" client host: %15s port: %d\n",
ip_str, ntohs(clients[i].sin_port));
}
}
break;
case '\n':
break;
default:
printf("unrecognized command %c\n", buf[0]);
break;
}
// must print a new prompt
printf("server > ");
}
static void
update_clients(int socketfd)
{
// Copy the state.
world_state_t tmp_world = world;
// Serialization Loop: convert to network byte order
for (int i = 0; i < MAX_PLAYERS; i++) {
if (tmp_world.players[i].active) {
tmp_world.players[i].x = (int)htonl((uint32_t)tmp_world.players[i].x); // little-endian -> big-endian
tmp_world.players[i].y = (int)htonl((uint32_t)tmp_world.players[i].y);
}
}
// Now that we converted the values we can send it to the client
for (int i = 0; i < MAX_PLAYERS; i++) {
// send to each active client the entire world
// set client_char so each client knows which character they are
if (world.players[i].active) {
tmp_world.client_char = world.players[i].symbol;
(void)sendto(socketfd, &tmp_world, sizeof(world_state_t), 0,
(struct sockaddr *)&clients[i], sizeof(struct sockaddr_in));
}
}
}
static void
handle_sigint(int sig)
{
(void)sig;
keep_running = 0;
}