一、网络通讯的流程
编写一个简单的C++网络通讯程序,通常涉及到以下几个步骤:创建套接字、绑定、监听、接受连接、发送和接收数据。以下是一个基本的TCP服务器和客户端的例子,演示了如何使用C++进行网络通讯。
TCP服务器:
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const 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(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(server_fd, 3) < 0) {
perror("listen");
close(server_fd);
exit(EXIT_FAILURE);
}
// 接受客户端连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
close(server_fd);
exit(EXIT_FAILURE);
}
// 接收客户端消息
read(new_socket, buffer, 1024);
std::cout << "Message from client: " << buffer << std::endl;
// 发送消息给客户端
send(new_socket, hello, strlen(hello), 0);
std::cout << "Hello message sent" << std::endl;
close(new_socket);
close(server_fd);
return 0;
}
TCP客户端
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
const char *hello = "Hello from client";
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cout << "Socket creation error" << std::endl;
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 转换IP地址
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cout << "Invalid address/ Address not supported" << std::endl;
return -1;
}
// 连接服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cout << "Connection Failed" << std::endl;
return -1;
}
// 发送消息给服务器
send(sock, hello, strlen(hello), 0);
std::cout << "Hello message sent" << std::endl;
// 接收服务器消息
read(sock, buffer, 1024);
std::cout << "Message from server: " << buffer << std::endl;
close(sock);
return 0;
}
这样,你就可以看到客户端和服务器之间的简单消息传递了。这是一个基础的TCP通讯示例,实际应用中可能需要更多的错误处理和功能扩展。