下面是一個(gè)簡(jiǎn)單的C++服務(wù)器端程序,利用recv函數(shù)接收數(shù)據(jù):
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
// 創(chuàng)建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;
}
// 監(jiān)聽端口
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);
// 接收數(shù)據(jù)
char buffer[1024] = {0};
int valread = recv(client_fd, buffer, 1024, 0);
std::cout << "Received: " << buffer << std::endl;
return 0;
}
這個(gè)程序創(chuàng)建一個(gè)服務(wù)器端socket,綁定端口,監(jiān)聽端口,并接受連接。接受到連接后,利用recv函數(shù)從客戶端接收數(shù)據(jù),并輸出到控制臺(tái)。