您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。