在 Linux 中进行 C++ 网络编程,通常需要使用套接字(socket)库
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
std::cerr << "Error creating socket" << std::endl;
return 1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "Error connecting to server" << std::endl;
return 1;
}
std::string message = "Hello, Server!";
if (send(sockfd, message.c_str(), message.size(), 0) < 0) {
std::cerr << "Error sending data" << std::endl;
return 1;
}
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
int received = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
if (received < 0) {
std::cerr << "Error receiving data" << std::endl;
return 1;
}
std::string response(buffer);
close(sockfd);
int server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (server_sockfd < 0) {
std::cerr << "Error creating server socket" << std::endl;
return 1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "Error binding server address" << std::endl;
return 1;
}
if (listen(server_sockfd, 10) < 0) {
std::cerr << "Error listening on server" << std::endl;
return 1;
}
struct sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(client_addr));
socklen_t client_addr_size = sizeof(client_addr);
int client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &client_addr_size);
if (client_sockfd < 0) {
std::cerr << "Error accepting client connection" << std::endl;
return 1;
}
std::string message = "Hello, Client!";
if (send(client_sockfd, message.c_str(), message.size(), 0) < 0) {
std::cerr << "Error sending data to client" << std::endl;
return 1;
}
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
int received = recv(client_sockfd, buffer, sizeof(buffer) - 1, 0);
if (received < 0) {
std::cerr << "Error receiving data from client" << std::endl;
return 1;
}
std::string response(buffer);
close(client_sockfd);
close(server_sockfd);
g++ -o server server.cpp
g++ -o client client.cpp
./server
./client
这个简单的示例展示了如何在 Linux 上使用 C++ 进行基本的网络编程。实际应用中,你可能需要处理错误、使用多线程或多进程处理多个客户端连接等。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。