欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > linux socket编程之udp_dict_serve服务端--引入配置文件

linux socket编程之udp_dict_serve服务端--引入配置文件

2025/5/14 23:10:41 来源:https://blog.csdn.net/qq_73955920/article/details/144668148  浏览:    关键词:linux socket编程之udp_dict_serve服务端--引入配置文件

注意:本篇博客只是对上一篇博客功能的增加

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词