diff options
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | Makefile | 5 | ||||
-rw-r--r-- | pd_server.c | 83 |
3 files changed, 88 insertions, 1 deletions
@@ -1,2 +1,3 @@ tit4tat prisoners_dilemma +pd_server @@ -1,8 +1,11 @@ -all: tit4tat prisoners_dilemma +all: pd_server tit4tat prisoners_dilemma tit4tat: tit4tat.c gcc -std=c99 -Wall -o $@ $< +pd_server: pd_server.c + gcc -o $@ $< + prisoners_dilemma: prisoners_dilemma.pl gplc -o $@ $< diff --git a/pd_server.c b/pd_server.c new file mode 100644 index 0000000..d0b2315 --- /dev/null +++ b/pd_server.c @@ -0,0 +1,83 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <errno.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> + +enum { + COORPERATION = 'c', + DEFECTION = 'd' +}; + +int pay(int a, int b) +{ + if (a == COORPERATION && b == DEFECTION) return 1; + if (a == DEFECTION && b == DEFECTION) return 2; + if (a == COORPERATION && b == COORPERATION) return 3; + if (a == DEFECTION && b == COORPERATION) return 4; + + exit(EXIT_FAILURE); +} + +int +main(int argc, char *argv[]) +{ + int sock, player[2], read_fd; + struct sockaddr_in serv_addr; + int port = 8068; + int rounds, i; + int optval = 1; + + rounds = atoi(argv[1]); + + sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0) + return EXIT_FAILURE; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + &optval, sizeof optval); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = INADDR_ANY; + serv_addr.sin_port = htons(port); + if (bind(sock, (struct sockaddr *) &serv_addr, + sizeof(serv_addr)) < 0) { + fprintf(stderr, "Failed to bind: %s\n", + strerror(errno)); + return EXIT_FAILURE; + } + listen(sock, 2); + + for (i = 0; i < 2; ++i) { + player[i] = accept(sock, NULL, NULL); + } + int a_payment = 0, b_payment = 0; + for (i = 0; i < rounds; ++i) { + char a, b; + read(player[0], &a, 1); + read(player[1], &b, 1); + + if (a != 'c' && a != 'd') { + printf("a sent incorrect char: %c\n", a); + continue; + } + if (b != 'c' && b != 'd') { + printf("b sent incorrect char: %c\n", b); + continue; + } + + a_payment += pay(a, b); + b_payment += pay(b, a); + + printf("A [%c]: %d Euro\tB [%c]: %d Euro\t\t\tA: %d\tB: %d\n", + a, pay(a, b), b, pay(b, a), a_payment, b_payment); + + write(player[0], &b, 1); + write(player[1], &a, 1); + } + close(player[0]); + close(player[1]); + close(sock); +} |