代码拉取完成,页面将自动刷新
#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
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。