下面是一個簡單的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函數從客戶端接收數據,并輸出到控制臺。