以下是一个简单的C++示例,展示了如何在客户端和服务器之间进行多次通信:
服务器端代码(server.cpp):
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
int main() {
int server_socket, new_socket, valread;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char* response = "已收到消息";
// 创建socket对象
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
std::cerr << "Socket creation failed" << std::endl;
return -1;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// 绑定主机和端口
if (bind(server_socket, (struct sockaddr*)&address, sizeof(address))<0) {
std::cerr << "Bind failed" << std::endl;
return -1;
}
// 监听连接请求
if (listen(server_socket, 3) < 0) {
std::cerr << "Listen failed" << std::endl;
return -1;
}
std::cout << "等待客户端连接..." << std::endl;
while(true) {
// 接受客户端连接
if ((new_socket = accept(server_socket, (struct sockaddr*)&address,
(socklen_t*)&addrlen))<0) {
std::cerr << "Accept failed" << std::endl;
return -1;
}
char client_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(address.sin_addr), client_ip, INET_ADDRSTRLEN);
std::cout << "与客户端 " << client_ip << " 建立连接" << std::endl;
while(true) {
// 接收客户端请求数据
valread = read(new_socket, buffer, 1024);
if (valread <= 0)
break;
std::cout << "接收到来自客户端的消息:" << buffer << std::endl;
// 处理请求并返回响应数据
send(new_socket, response, strlen(response), 0);
memset(buffer, 0, sizeof(buffer));
}
// 关闭与该客户端的连接
close(new_socket);
}
// 关闭服务器socket对象
close(server_socket);
return 0;
}
客户端代码(client.cpp):
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#define PORT 8080
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
const char* server_ip = "127.0.0.1";
char buffer[1024] = {0};
// 创建socket对象
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(PORT);
// 将IPv4地址从点分十进制转换为二进制形式
if(inet_pton(AF_INET, server_ip, &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;
}
while(true) {
// 获取用户输入的消息
char message[1024];
std::cout << "请输入要发送的消息:";
fgets(message, sizeof(message), stdin);
// 发送消息给服务器
send(sock , message , strlen(message) , 0 );
if (strncmp(message, "quit", 4) == 0)
break;
memset(buffer, 0, sizeof(buffer));
// 接收服务器的响应数据
read(sock, buffer, sizeof(buffer));
std::cout << "接收到来自服务器的响应:" << buffer << std::endl;
}
// 关闭客户端socket对象
close(sock);
return 0;
}
在该示例中,编译并分别运行server.cpp和client.cpp。客户端可以多次输入消息发送给服务器,并接收服务器的响应数据。当输入”quit”时,连接将关闭。
请注意,此示例仅用于演示目的,并未处理错误处理和其他细节。在实际情况下,可能需要更复杂的逻辑来处理通信和异常情况。
内容由零声教学AI助手提供,问题来源于学员提问