C++网络通信核心技术解析

发表时间: 2024-07-28 15:50

在C++中实现Socket网络通信,确保开发环境支持网络编程。在大多数Linux发行版和Windows上,你都可以直接进行网络编程。在Windows上,你可能需要安装额外的库如Winsock。

1. 服务器端代码

创建一个套接字,绑定到一个端口,监听来自客户端的连接,并接收来自客户端的消息。

#include <iostream>

#include <sys/socket.h>

#include <netinet/in.h>

#include <unistd.h>

#include <string.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};

// 创建套接字

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {

perror("socket failed");

exit(EXIT_FAILURE);

}

// 强制绑定套接字到端口8080

if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {

perror("setsockopt");

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");

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;

// 关闭套接字

close(server_fd);

return 0;

}

2. 客户端代码

客户端将连接到服务器,并发送一条消息。

#include <iostream>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <string.h>

#define PORT 8080

int main() {

struct sockaddr_in serv_addr;

int sock = 0;

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);

// 将IPv4地址从文本转换为二进制形式

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;

}

std::string message = "Hello from client";

send(sock, message.c_str(), message.length(), 0);

// 关闭套接字

close(sock);

return 0;

}