根据代码的运行结果,客户端连接后立即显示连接失败的问题可能是由于服务器在处理客户端请求后立即关闭了连接,导致客户端读取数据时出现连接断开的情况。可以尝试延迟关闭连接的操作,等待客户端读取完数据后再关闭连接。

在服务器代码中,可以将关闭连接的操作放在handleClientRequest函数的末尾,即在发送建议后关闭连接。修改代码如下:

void handleClientRequest(ServerContext *context) {
    // ... 处理客户端请求的代码 ...

    // 向客户端发送建议
    ssize_t sendSize = send(context->sockfd, suggestion, strlen(suggestion), 0);
    if (sendSize == -1) {
        perror("发送失败\nsend");
        return;
    }
    printf("%s\n", suggestion);
    // 关闭连接
    shutdown(context->sockfd, SHUT_RDWR);
}

这样修改后,服务器在发送建议后才关闭连接,客户端就有足够的时间读取服务器发送的数据,避免连接断开的问题。重新编译和运行服务器和客户端代码,看看是否能够解决连接失败的问题。

服务器代码#include stdioh#include stdlibh#include stringh#include unistdh#include syssocketh#include sysselecth#include arpaineth#include sqlite3h#include netinetinh#define MAX_BUFFER_SIZE 1024typedef stru

原文地址: https://www.cveoy.top/t/topic/iBM1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录