在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;
char buffer[1024];
// 创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
std::cerr << "Error creating socket" << std::endl;
return 1;
}
// 配置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &(server_addr.sin_addr));
// 连接服务器
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "Error connecting to server" << std::endl;
return 1;
}
// 设置接收缓冲区大小
int recv_buffer_size = 4096;
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recv_buffer_size, sizeof(recv_buffer_size)) < 0) {
std::cerr << "Error setting receive buffer size: " << strerror(errno) << std::endl;
return 1;
}
// 设置发送缓冲区大小
int send_buffer_size = 4096;
if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &send_buffer_size, sizeof(send_buffer_size)) < 0) {
std::cerr << "Error setting send buffer size: " << strerror(errno) << std::endl;
return 1;
}
// 向服务器发送数据
std::string message = "Hello, server!";
if (send(sockfd, message.c_str(), message.size(), 0) < 0) {
std::cerr << "Error sending data: " << strerror(errno) << std::endl;
return 1;
}
// 从服务器接收数据
ssize_t recv_len = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
if (recv_len < 0) {
std::cerr << "Error receiving data: " << strerror(errno) << std::endl;
return 1;
}
buffer[recv_len] = '\0';
std::cout << "Received from server: " << buffer << std::endl;
// 关闭套接字
close(sockfd);
return 0;
}
在这个示例中,我们首先创建了一个套接字,然后配置了服务器地址。接下来,我们连接到服务器,并使用setsockopt
函数分别设置了接收缓冲区和发送缓冲区的大小。最后,我们向服务器发送数据并接收响应。