用c++中写出客户端和服务端代码利用udp协议引入txt文档进行机器人一问一答,而不是直接把文档的所有内容打印出来。
时间: 2024-01-24 16:17:19 浏览: 57
以下是一个简单的UDP协议实现的机器人一问一答的客户端和服务端代码,其中客户端会从txt文档中读取问题,发送给服务端,服务端接收到问题后回复答案给客户端:
服务端代码:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fstream>
using namespace std;
#define PORT 8080
int main(int argc, char const *argv[]) {
int sock = 0;
struct sockaddr_in serv_addr, cli_addr;
int len = sizeof(cli_addr);
char buffer[1024] = {0};
char resp[1024] = {0};
// 创建UDP套接字
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket failed");
return -1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
// 设置服务器地址结构体
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(PORT);
// 绑定套接字到指定端口
if (bind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("bind failed");
return -1;
}
while (1) {
cout << "Waiting for client request..." << endl;
// 从客户端接收数据
int n = recvfrom(sock, (char *)buffer, 1024, MSG_WAITALL, (struct sockaddr *)&cli_addr, (socklen_t *)&len);
buffer[n] = '\0';
cout << "Client: " << buffer << endl;
// 从txt文档中读取答案
string question = string(buffer);
string answer = "";
ifstream infile("qa.txt");
string line;
while (getline(infile, line)) {
if (line == question) {
getline(infile, answer);
break;
}
}
infile.close();
// 回复客户端答案
strcpy(resp, answer.c_str());
sendto(sock, (const char *)resp, strlen(resp), MSG_CONFIRM, (const struct sockaddr *)&cli_addr, len);
}
close(sock);
return 0;
}
```
客户端代码:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fstream>
using namespace std;
#define PORT 8080
int main(int argc, char const *argv[]) {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
char resp[1024] = {0};
// 创建UDP套接字
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket failed");
return -1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
// 设置服务器地址结构体
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
while (1) {
// 读取问题
string question;
cout << "Enter your question: ";
getline(cin, question);
// 发送数据到服务器
sendto(sock, question.c_str(), question.length(), MSG_CONFIRM, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
// 从服务器接收答案
int n = recvfrom(sock, (char *)resp, 1024, MSG_WAITALL, (struct sockaddr *)&serv_addr, (socklen_t *)&len);
resp[n] = '\0';
cout << "Server: " << resp << endl;
}
close(sock);
return 0;
}
```
在这个例子中,我们假设有一个qa.txt文件,其中包含了一些问题和对应的答案,每个问题和答案都占据一行,使用冒号分隔。例如:
```
What is the capital of France?:Paris
What is the largest ocean?:Pacific
```
当客户端发送一个问题给服务端时,服务端会从qa.txt文件中查找对应的答案,并将答案回复给客户端。
阅读全文