C++的网络编程方法主要涉及到使用套接字(sockets)来实现网络通信,包括TCP和UDP两种主要的协议。以下是C++网络编程的基本方法、例子以及常用的库:
一个简单的C++ TCP服务器和客户端的示例代码展示了如何使用C++标准库进行网络通信:
服务器端代码示例:
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// 创建套接字文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
// 绑定套接字到端口8080
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 读取数据
read(new_socket, buffer, 1024);
std::cout << "Message from client: " << buffer << std::endl;
// 发送数据
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// 关闭套接字
close(new_socket);
close(server_fd);
return 0;
}
客户端代码示例:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cerr << "socket creation error" << std::endl;
return -1;
}
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 << "inet_pton() failed" << std::endl;
return -1;
}
// 连接服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cerr << "connect() failed" << std::endl;
return -1;
}
// 发送数据
send(sock, hello, strlen(hello), 0);
// 接收数据
char buffer[1024] = {0};
read(sock, buffer, 1024);
std::cout << "Server response: " << buffer << std::endl;
// 关闭套接字
close(sock);
return 0;
}
通过上述方法和库,C++开发者可以构建高效、可靠的网络应用程序。