提问人:XXXCprt 提问时间:11/9/2023 最后编辑:Remy LebeauXXXCprt 更新时间:11/11/2023 访问量:53
在套接字编程 UDP 中从服务器接收消息时出现问题
Problem with receiving message from server in socket programming UDP
问:
我的任务是用 C 语言创建一个具有 3 个服务器和一个客户端的代码。客户端启动后,它应该无限期地在端口上侦听新服务器到达的通知。
我想出了服务器将发送 hello 消息的代码,当客户端收到消息时,它会将服务器添加到已知服务器列表中。但客户根本没有收到它。
客户端逻辑:
int bytes_received = recvfrom(client_socket, buffer, MAX_BUFFER_SIZE, 0, NULL, NULL);
if (bytes_received == -1) {
printf("ERROR: %s (%s:%d)\n", strerror(errno), __FILE__, __LINE__);
exit(-1);
}
buffer[bytes_received] = '\0';
if (strncmp(buffer, "HELLO: ", 7) == 0) {
char *content = buffer + 7;
printf("Received HELLO message from server: %s\n", content);
printf("Received HELLO message from (%s:%d): %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer + 1);
if (num_known_servers < MAX_SERVERS) {
struct Server new_server;
memcpy(&new_server.addr, (struct sockaddr_in *)(&client_addr), sizeof(struct sockaddr_in));
new_server.last_message_time = time(NULL);
known_servers[num_known_servers++] = new_server;
char log_message[MAX_BUFFER_SIZE];
snprintf(log_message, MAX_BUFFER_SIZE, "New server discovered at %s:%d", inet_ntoa(new_server.addr.sin_addr), ntohs(new_server.addr.sin_port));
logMessage(log_message);
}
} else if {
continue;
}
服务器逻辑:
char server_message[] = "HELLO: Hello from server";
if (sendto(server_socket, server_message, strlen(server_message), 0, (struct sockaddr *)&client_addr, sizeof(client_addr)) == -1) {
printf("ERROR: %s (%s:%d)\n", strerror(errno), __FILE__, __LINE__);
exit(-1);
}
答: 暂无答案
评论
(struct sockaddr_in *)(&client_addr)
这是一个鱼腥的演员阵容。声明为什么类型?client_addr
strlen(server_message)
strlen(server_message)+1
sizeof(server_message)
else if { continue }
==> 你是说吗?else { continue }