Ai
1 Star 0 Fork 0

lsnmjp/code of cpp Linux 算法

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
UDP_Server.hpp 2.76 KB
一键复制 编辑 原始数据 按行查看 历史
lsnmjp 提交于 2025-06-19 13:13 +08:00 . echo_server_v1
#ifndef UDP_SERVER__HPP
#define UDP_SERVER__HPP
#include <iostream>
#include <memory>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Commn.hpp"
using namespace LogModule;
//global
int gsockfd = -1;
const static std::string gdefaultIP = "127.0.0.1";
const static uint16_t gdefaultport = 8080;
class UdpServer
{
public:
UdpServer(uint16_t port = gdefaultport , const std::string& IP = gdefaultIP)
:_sockfd(gsockfd)
,_port(port)
,_IP(IP)
{
}
void InitServer()
{
//ENABLE_FILE_LOG;//日志文件使能
ENABLE_CONSOLE_LOG;
//1.创建套接字
_sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
if(_sockfd<0)
{
Die(1);
LOG(LogLevel::FATAL)<<"socket: "<<strerror(errno);
}
//创建成功,看看套接字
LOG(LogLevel::INFO)<<"socket success , socket fd is :"<<_sockfd;
//2.填充网络信息并bind : 设置进了内核中
struct sockaddr_in* in_addr_;
in_addr_ = new sockaddr_in();
//2.1 填充in_addr的信息
bzero(in_addr_, sizeof(sockaddr_in));//清理
in_addr_->sin_family = AF_INET;
in_addr_->sin_port = ::htons(_port);//端口号
in_addr_->sin_addr.s_addr = ::inet_addr(_IP.c_str());//1. string ip->4bytes 2. network order
//bind
int n = bind(_sockfd,CONV(in_addr_),sizeof(sockaddr_in));
if(n < 0)
{
LOG(LogLevel::ERROR)<<"bind fail";
exit(1);
}
LOG(LogLevel::INFO)<<"bind success";
}
void Start()
{
_isrunning = true;
while(true)
{
char inbuffer[SIZE];
sockaddr_in peer;
socklen_t peer_len = sizeof(peer);
int n = recvfrom(_sockfd,inbuffer,sizeof(inbuffer)-1,0,CONV(&peer),&peer_len);
if(n>0)
{
inbuffer[n] = 0;
LOG(LogLevel::DEBUG)<<"Client says@ "<<inbuffer;
std::string echo = "#echo: ";
echo += inbuffer;
int ret = sendto(_sockfd,echo.c_str(),echo.length(),0,CONV(&peer),peer_len);
if(ret>0)
{
LOG(LogLevel::DEBUG)<<"server sendto success";
}
else
{
LOG(LogLevel::DEBUG)<<"server sendto fail";
}
}
}
_isrunning = false;
}
~UdpServer()
{
}
private:
int _sockfd; //访问套接字的文件描述符
uint16_t _port; //端口号
std::string _IP;//十进制点分IP地址
bool _isrunning = false;
};
#endif
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/lsnmjp/code-of-cpp-linux-algorithm.git
git@gitee.com:lsnmjp/code-of-cpp-linux-algorithm.git
lsnmjp
code-of-cpp-linux-algorithm
code of cpp Linux 算法
master

搜索帮助