在Linux环境下使用C++进行网络编程,通常会使用套接字(socket)API。以下是一个简单的网络编程入门指南,包括了创建一个基本的TCP服务器和客户端。
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
std::cerr << "Could not create socket" << std::endl;
return -1;
}
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY; // 监听所有网络接口
address.sin_port = htons(8080); // 端口号
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
std::cerr << "Bind failed" << std::endl;
return -1;
}
if (listen(server_fd, 3) < 0) {
std::cerr << "Listen failed" << std::endl;
return -1;
}
int new_socket;
struct sockaddr_in client_address;
socklen_t addrlen = sizeof(client_address);
new_socket = accept(server_fd, (struct sockaddr *)&client_address, &addrlen);
if (new_socket < 0) {
std::cerr << "Accept failed" << std::endl;
return -1;
}
char buffer[1024] = {0};
read(new_socket, buffer, 1024);
std::cout << "Message from client: " << buffer << std::endl;
send(new_socket, "Hello from server", 17, 0);
close(new_socket);
close(server_fd);
包含必要的头文件(与服务器相同)。
创建套接字:
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
std::cerr << "Could not create socket" << std::endl;
return -1;
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cerr << "Invalid address/ Address not supported" << std::endl;
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cerr << "Connection Failed" << std::endl;
return -1;
}
std::string message = "Hello from client";
send(sock, message.c_str(), message.size(), 0);
char buffer[1024] = {0};
read(sock, buffer, 1024);
std::cout << "Message from server: " << buffer << std::endl;
close(sock);
在终端中,使用g++编译服务器和客户端程序:
g++ -o server server.cpp
g++ -o client client.cpp
运行服务器:
./server
在另一个终端中运行客户端:
./client
这样,你就创建了一个简单的TCP服务器和客户端,它们可以相互通信。这只是一个非常基础的例子,实际的网络编程会更加复杂,涉及到错误处理、多线程或多进程处理、安全性等多个方面。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:Linux C++网络编程怎样入门