阅读量:0
下面是一个简单的C++服务器端程序,利用recv函数接收数据:
#include <iostream> #include <cstring> #include <sys/socket.h> #include <netinet/in.h> int main() { // 创建socket int server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd == -1) { std::cerr << "Error creating socket" << std::endl; return 1; } // 绑定端口 struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(8888); if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { std::cerr << "Bind failed" << std::endl; return 1; } // 监听端口 listen(server_fd, 3); // 接受连接 int client_fd; struct sockaddr_in client_addr; int addr_len = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t *)&addr_len); // 接收数据 char buffer[1024] = {0}; int valread = recv(client_fd, buffer, 1024, 0); std::cout << "Received: " << buffer << std::endl; return 0; }
这个程序创建一个服务器端socket,绑定端口,监听端口,并接受连接。接受到连接后,利用recv函数从客户端接收数据,并输出到控制台。