首页 > 解决方案 > 将 Int 值写入服务器是在套接字编程 C 中将其转换为 -1

问题描述

嗨,我正试图将一个 int 从我的客户端写入我的服务器。我在客户端的写入设置如下:

/* Writes an int to the server socket. */
void write_server_int(int sockfd, int msg)
{
    printf("\n[DEBUG] THIS IS the Message: %d", msg);
    printf("\n[DEBUG] THIS IS size of the Message: %lu", sizeof(msg));


    int n = write(sockfd, &msg, sizeof(msg));
    printf("\n[DEBUG] THIS IS N: %d", n);
    if (n < 0)
        error("ERROR writing int to server socket");

    printf("[DEBUG] Wrote int to server: %d\n", msg);
}

我在服务器端的接收设置如下:

/* Reads an int from a client socket. */
int recv_int(int cli_sockfd)
{
    int msg = 0;
    int n = read(cli_sockfd, &msg, sizeof(msg));

    if (n < 0 || n != sizeof(int)) /* Not what we were expecting. Client likely disconnected. */
        return -1;

    printf("[DEBUG] Received int: %d\n", msg);

    return msg;
}

我从这里调用我的函数:

while(1) {
        option = menu_screen(sockfd); // Get Menu Screen and Clients Choosen Option
        printf("[DEBUG] User selection menu option: %d\n", option);

        while (option == 1){ // Gameplay Option
            draw_board(board);
            recv_msg(sockfd, msg);
            if (!strcmp(msg, "TRN")) { /* Take a turn. */
                int choice = take_turn_member(sockfd);
                write_server_int(sockfd, choice);
            }
            if (!strcmp(msg, "COX")){
                int coordinates_x = take_turn_coord_x();
                printf("\n[DEBUG] Coordinates X is: %d", coordinates_x);
                write_server_int(sockfd, coordinates_x);
                printf("\n\nMADE IT HERE");
            }
            if (!strcmp(msg, "COY")){
                int coordinates_y = take_turn_coord_y();
                printf("\n[DEBUG] Coordinates Y is: %d", coordinates_y);
                write_server_int(sockfd, coordinates_y);
                printf("\n\nMADE IT HERE");
            }
}

我的代码可以完美运行,直到它 write_server_int(sockfd, coordinates_x);从控制台输出到达此处,这表明传入的 int 正在write_server_int()以 -1 的形式推送到服务器。

[DEBUG] Received message: COX
Enter Row Tile Coordinates A-I : A

[DEBUG] Coordinates X is: 0
THIS IS the Message: 0
THIS IS size of the Message: 4
THIS IS N: -1
Either the server shut down or the other player disconnected.
Game over.

有人可以向我解释发生了什么以及如何解决它吗?

标签: csocketstcpclient-server

解决方案


来自控制台输出的此处显示正在传递给 write_server_int() 的 int 正在作为 -1 推送到服务器。

不,你的输出说,结果write()-1

int n = write(sockfd, &msg, sizeof(msg));
printf("\n[DEBUG] THIS IS N: %d", n);

[DEBUG] Coordinates X is: 0
THIS IS the Message: 0
THIS IS size of the Message: 4
THIS IS N: -1 <------------------------ mind the 'N'

推荐阅读