您好,登錄后才能下訂單哦!
在C++中,使用Socket庫構(gòu)建服務(wù)端需要遵循以下步驟:
#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;
// 處理請求并發(fā)送響應(yīng)
std::string response = "Hello from server!";
send(client_fd, response.c_str(), response.size(), 0);
}
close(client_fd);
close(server_fd);
將以上代碼片段組合在一起,即可創(chuàng)建一個簡單的C++ Socket服務(wù)端。注意,這個示例僅適用于TCP連接。如果你需要創(chuàng)建一個UDP服務(wù)端,需要使用socket(AF_INET, SOCK_DGRAM, 0)
替換創(chuàng)建socket的行,并使用recvfrom()
和sendto()
函數(shù)處理數(shù)據(jù)包的接收和發(fā)送。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。