/* * Read a stream socket one line at a time, and write each line back * to the sender. * * Return when the connection is terminated. */ #include #include "common.h" #include "logic.h" #include "network.h" #define MAXSIZE 512 char **board2buf(int board[SIZE][SIZE]) { char **buf = malloc(SIZE * sizeof(char *)); for (int i = 0; i < SIZE; i++) buf[i] = malloc((SIZE + 2) * sizeof(char)); for(int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { // Coordinates alternation buf[i][j] = board[j][i] + '0'; } buf[i][SIZE] = '\n'; buf[i][SIZE+1] = '\0'; } return buf; } void senddata(int sockfd, int code, char **buf) { char out[MAXSIZE]; int n; if (code == rp_ok) { sprintf(out, "1\n"); for (int i = 0; i < SIZE; i++) { strcat(out, buf[i]); } } else { sprintf(out, "0\n"); } fprintf(stderr, "Sending: %s", out); n = strlen(out); if (writen(sockfd, out, n) != n) fprintf(stderr, "str_echo: writen error\n"); } str_echo(int sockfd) { int wait = 0; int n; int res; int last = 2; int x, y, c; char line[MAXSIZE]; for ( ; ; ) { n = readline(sockfd, line, MAXSIZE); if (n == 0) { fprintf(stderr, "Connection terminated\n"); return; /* connection terminated */ } else if (n < 0) fprintf(stderr, "str_echo: readline error\n"); fprintf(stderr, "Received: %s", line); if (!wait) { if (line[0] == '0') { res = init(); } else if (line[0] == '1') { res = 0; wait = 1; } if (res) { last = c; senddata(sockfd, rp_ok, board2buf(board)); } else { senddata(sockfd, rp_error, NULL); } } else { sscanf(line, "%d,%d,%d", &x, &y, &c); if (c == last) { senddata(sockfd, rp_error, NULL); } else { res = place(x, y, c); if (res) { last = c; senddata(sockfd, rp_ok, board2buf(board)); } else { senddata(sockfd, rp_error, NULL); } } wait = 0; } } }