注意:本篇博客只是对上一篇博客功能的增加
1.创建配置文件(翻译)
Dict.txt
apple: 苹果
banana: 香蕉
cat: 猫
dog: 狗
book: 书
pen: 笔
happy: 快乐的
sad: 悲伤的
run: 跑
jump: 跳
teacher: 老师
student: 学生
car: 汽车
bus: 公交车
love: 爱
hate: 恨
hello: 你好
goodbye: 再见
summer: 夏天
winter: 冬天
2.定义Dict类
#include<string>
#include<fstream>
#include<unordered_map>
#include"log.hpp"class Dict
{//默认配置文件路径const std::string default_path = "./Dict.txt";//默认分隔符const std::string sep = ": ";
private://将配置文件的内容加载到_dict中bool Load(){std::ifstream file(_dict_conf_file_path);if(!file.is_open()){LOG(FATAL,"open %s error",_dict_conf_file_path);return false;}//按行读取文件std::string line;while(getline(file,line)){if(line == "") continue;std::string word;size_t pos = line.find(sep);word = line.substr(0,pos);std::string han;han = line.substr(pos+sep.size());//将对应的key value插入到哈希桶中_dict.insert(make_pair(word,han));LOG(DEBUG,"load info %s: %s\n",word,han);}file.close();return true;}
public:Dict(const std::string &path = "./Dict.txt"):_dict_conf_file_path(path){Load();}std::string TranSlate(const std::string &word){auto han = _dict.find(word);if(han == _dict.end()){return "这个单词未找到";}return han->second;}~Dict(){}
private://key value 结构的字典 单词 翻译std::unordered_map<std::string,std::string> _dict;//配置文件的目录std::string _dict_conf_file_path;
};
3.main函数中将翻译模块和网络模块分开
//翻译模块Dict dict;//网络模块//智能指针创建UdpServerstd::unique_ptr<UdpServer> usvr = std::make_unique<UdpServer>( port,std::bind(&Dict::TranSlate,&dict,std::placeholders::_1) );
//启动UdpServervoid Stat(){_running = true;//服务器一般都是死循环while(true){sockaddr_in peer;//recvfrom的最后一个参数类型是socklen_tsocklen_t len = sizeof(peer);char buffer[1024];//从接收缓存区中读取数据报int n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);//读取到数据才做处理,否则什么都不做if(n > 0){buffer[n] = 0;//打印是哪个客户端发来的消息InetAddr addr(peer);LOG(INFO,"message form[%s:%d]: %s\n",addr.GetIp().c_str(),addr.Get_Port(),buffer);//将翻译发送给对方std::string response = _func(buffer);sendto(_sockfd,response.c_str(),response.size(),0,(sockaddr*)&peer,len);}}_running = false;}