c - 将 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.
有人可以向我解释发生了什么以及如何解决它吗?
解决方案
来自控制台输出的此处显示正在传递给 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'
推荐阅读
- amazon-web-services - 如何使用 crontab 自动启动 AWS EC2 实例?
- python - 使用 Selenium/Python/Chrome 从 PDF 查看器下载 PDF
- python-3.x - 模板加载器不查看 DIRS 中定义的目录
- c++ - 异常安全:强保证 vs 基本保证
- python - conda 4.9.2 是否报告虚假包冲突?
- django - Django - 直接使用 Model 类来避免显式地编写 Form 类
- c# - 通过 Stream 读取 Xml 文件的一部分,而不是只读取一个
- angular - 尝试在 Angular Google Maps 项目中加载GeoJson 时出现 400 错误
- c# - Windows 窗体项目无法识别来自另一个项目的类
- javascript - 你可能需要一个合适的加载器来处理这个文件类型错误反应