I'm trying to write a client and server as an exercise in learning the sockets api. The client needs to send the server 2 integers to provide X,Y coordinates for a "move" in a game of tic-tac-toe. The server just verifies that the coordinates are in range. If they're not a text string is sent back. If they are then the two coordinates are sent back to the client. If i have:
Code: Select all
void get_player_move(void)
{
int len;
int n=0;
char sendline[16], recvline[30];
int x, y;
printf("Enter X,Y coordinates for your move: ");
scanf( "%d%d", &x, &y);
snprintf(sendline, sizeof(sendline), "%c%c\n", x, y);
for(;;) {
if(n > 0) {
printf("Enter X,Y coordinates for your move: ");
scanf("%d%d", &x, &y);
snprintf(sendline, sizeof(sendline), "%c%c\n", x, y);
}
if(sendto(sockfd, sendline, sizeof(sendline), 0, res->ai_addr, res->ai_addrlen) ==-1){
perror("sendto failed");
exit(1);
}
if(recvfrom(sockfd, recvline, sizeof(recvline), 0, res->ai_addr, &res->ai_addrlen) ==-1){
perror("recvfrom failed");
exit(1);
}
if(sscanf(recvline, "%d%d", &x, &y) == 2)
break;
else
printf("%s\n", recvline);
n++;
}
matrix[x][y] = 'X';
}Code: Select all
void get_player_move(void)
{
char recvline[16], sendline[30], textline[30];
int x, y;
for(;;){
if(recvfrom(sockfd, recvline, sizeof(recvline), 0,(struct sockaddr*)&cli_addr, &cli_len) ==-1){
perror("recvfrom error");
exit(1);
}
if(sscanf(recvline, "%d%d", &x, &y) != 2){
perror("sscanf error on server");
exit(1);
}
x--; y--;
printf("x is %d, y is %d\n", x, y);
if(matrix[x][y] != ' '){
snprintf(textline, sizeof(textline), "Invalid move, try again.\n");
if(sendto(sockfd, textline, sizeof(textline), 0, (struct sockaddr*)&cli_addr,cli_len) ==-1){
perror("sendto failed");
exit(1);
}
}
else {
matrix[x][y] = 'X';
snprintf(sendline, sizeof(sendline), "%c%c\n", x, y);
if(sendto(sockfd, sendline, sizeof(sendline), 0, (struct sockaddr*)&cli_addr, cli_len) ==-1){
perror("send move back failed");
exit(1);
}
else
/*break;*/
exit(0);
}
}
}
Thank you very much for any help

