在C++中,使用Socket库构建服务端需要遵循以下步骤:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int server_fd, client_fd, addr_len;
struct sockaddr_in server_addr, client_addr;
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
std::cerr << "socket creation failed" << std::endl;
return -1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8080);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "bind failed" << std::endl;
return -1;
}
if (listen(server_fd, 3) < 0) {
std::cerr << "listen" << std::endl;
return -1;
}
addr_len = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t *)&addr_len);
if (client_fd < 0) {
std::cerr << "accept" << std::endl;
return -1;
}
char buffer[1024] = {0};
while (true) {
read(client_fd, buffer, 1024);
std::cout << "Received from client: " << buffer << std::endl;
// 处理请求并发送响应
std::string response = "Hello from server!";
send(client_fd, response.c_str(), response.size(), 0);
}
close(client_fd);
close(server_fd);
将以上代码片段组合在一起,即可创建一个简单的C++ Socket服务端。注意,这个示例仅适用于TCP连接。如果你需要创建一个UDP服务端,需要使用socket(AF_INET, SOCK_DGRAM, 0)
替换创建socket的行,并使用recvfrom()
和sendto()
函数处理数据包的接收和发送。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。