V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
TimeNewRome
V2EX  ›  问与答

[不懂就问] 为什么我的 socket 总是断断续续地出现 Connect failed

  •  
  •   TimeNewRome · 86 天前 · 685 次点击
    这是一个创建于 86 天前的主题,其中的信息可能已经有所发展或是发生改变。
    3 条回复
    TimeNewRome
        1
    TimeNewRome  
    OP
       86 天前
    以下是 client 端代码:

    void send(const std::string& message) {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
    std::cerr << "Could not create socket" << std::endl;
    return;
    }

    int sendBufferSize = 65536;
    if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sendBufferSize, sizeof(sendBufferSize)) < 0) {
    std::cerr << "Could not set send buffer size" << std::endl;
    close(sock);
    return;
    }

    sockaddr_in server;
    server.sin_addr.s_addr = inet_addr("10.130.9.6");
    server.sin_family = AF_INET;
    server.sin_port = htons(8091);

    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
    std::cerr << "Connect failed. Error" << std::endl;
    close(sock);
    return;
    }

    if (send(sock, message.c_str(), message.length(), 0) < 0) {
    std::cerr << "Send failed" << std::endl;
    }

    close(sock);
    }
    TimeNewRome
        2
    TimeNewRome  
    OP
       86 天前
    以下是 server 端代码:

    int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[32768] = {0};

    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
    perror("socket failed");
    exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(8091);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
    perror("bind failed");
    close(server_fd);
    exit(EXIT_FAILURE);
    }

    if (listen(server_fd, 3) < 0) {
    perror("listen");
    close(server_fd);
    exit(EXIT_FAILURE);
    }

    while (true) {
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
    perror("accept");
    close(server_fd);
    exit(EXIT_FAILURE);
    }

    int valread = read(new_socket, buffer, 1024);
    if (valread > 0) {
    std::cout << buffer << std::endl;
    memset(buffer, 0, sizeof(buffer));
    }

    close(new_socket);
    }

    close(server_fd);
    return 0;
    }
    TimeNewRome
        3
    TimeNewRome  
    OP
       86 天前
    使用 perror 函数的输出结果是“Connect failed: Cannot assign requested address.”
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   848 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 21:46 · PVG 05:46 · LAX 13:46 · JFK 16:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.