温馨提示×

c++ setsockopt怎样设置接收缓冲区

c++
小樊
81
2024-12-04 00:39:38
栏目: 编程语言

在C++中,使用setsockopt()函数可以设置套接字的选项

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main() {
    int sockfd;
    struct sockaddr_in server_addr;
    int recv_buffer_size = 4096; // 设置接收缓冲区大小为4KB

    // 创建套接字
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        std::cerr << "Error creating socket" << std::endl;
        return 1;
    }

    // 配置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    // 连接到服务器
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        std::cerr << "Error connecting to server" << std::endl;
        return 1;
    }

    // 设置接收缓冲区大小
    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recv_buffer_size, sizeof(recv_buffer_size)) == -1) {
        std::cerr << "Error setting receive buffer size" << std::endl;
        return 1;
    }

    std::cout << "Receive buffer size set to " << recv_buffer_size << " bytes" << std::endl;

    // 接收数据
    char buffer[recv_buffer_size];
    ssize_t received = recv(sockfd, buffer, recv_buffer_size, 0);
    if (received == -1) {
        std::cerr << "Error receiving data" << std::endl;
        return 1;
    }

    std::cout << "Received " << received << " bytes: " << std::string(buffer, received) << std::endl;

    // 关闭套接字
    close(sockfd);

    return 0;
}

在这个示例中,我们首先创建了一个套接字,然后配置了服务器地址。接下来,我们使用setsockopt()函数设置了接收缓冲区的大小。最后,我们接收了一些数据并打印出来。

0