您好,登錄后才能下訂單哦!
在C++中,使用socket庫可以實現(xiàn)多線程并發(fā)模型。以下是一個簡單的示例,展示了如何使用C++的socket庫和線程庫實現(xiàn)并發(fā)服務(wù)器:
#include <iostream>
#include <thread>
#include <vector>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
const int PORT = 8080;
const int BUFFER_SIZE = 1024;
void handle_client(int client_socket) {
char buffer[BUFFER_SIZE];
while (true) {
ssize_t bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0);
if (bytes_received == 0) {
break;
}
buffer[bytes_received] = '\0';
std::cout << "Received from client: " << buffer << std::endl;
send(client_socket, buffer, bytes_received, 0);
}
close(client_socket);
}
int main() {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -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(PORT);
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
std::cerr << "Error binding socket" << std::endl;
return 1;
}
if (listen(server_socket, 5) == -1) {
std::cerr << "Error listening on socket" << std::endl;
return 1;
}
std::vector<std::thread> threads;
while (true) {
struct sockaddr_in client_addr;
socklen_t client_addr_size = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_size);
if (client_socket == -1) {
std::cerr << "Error accepting client connection" << std::endl;
continue;
}
threads.push_back(std::thread(handle_client, client_socket));
}
for (auto &thread : threads) {
thread.join();
}
close(server_socket);
return 0;
}
在這個示例中,服務(wù)器首先創(chuàng)建一個socket,然后綁定到指定的端口上。接下來,服務(wù)器開始監(jiān)聽客戶端連接請求。當(dāng)接收到一個連接請求時,服務(wù)器會創(chuàng)建一個新的線程來處理客戶端的請求。這樣,服務(wù)器就可以同時處理多個客戶端連接,實現(xiàn)了并發(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)容。