编程语言
首页 > 编程语言> > handy源码阅读(六):udp类

handy源码阅读(六):udp类

作者:互联网

分为UdpServer类和UdpConn类。

struct UdpServer : public std::enable_shared_from_this<UdpServer>, private noncopyable {
  UdpServer(EventBases* bases);
int bind(const std::string& host, unsigned short port, bool reusePort = false);
static UpdServerPtr startServer(EventBases* bases, const std::string& short, unsigned short port, bool reusePort = false);
~UdpServer() {
delete channel_;
}
Ip4Addr getAddr() {
return addr_;
}
EventBase* getBase() {
return base_;
}
void sendTo(Buffer msg, Ip4Addr addr) {
sendTo(msg.data(), msg.size(), addr);
msg.clear();
}
void sendTo(const char* buf, size_t len, Ip4Addr addr);
void sendTo(const std::string& s, Ip4Addr addr) {
sendTo(s.data(), s.size(), addr);
}
void sendTo(const char* s, Ip4Addr addr) {
sendTo(s, strlen(s), addr);
}

void onMsg(const UdpSvrCallBack& cb) {
msgcb_ = cb;
}

private:
EventBase* base_;
EventBases* bases_;
Ip4Addr addr_;
Channel* channel_;
UdpSvrCallBack msgcb_; };

其中:

typedef std::shared_ptr<UdpConn> UdpConnPtr;
typedef std::shared_ptr<UdpServer> UdpServerPtr;
typedef std::function<void(const UdpConnPtr&, Buffer)> UdpCallBack;
typedef std::function<void(const UdpServerPtr&, Buffer, Ip4Addr)> UdpSvrCallBack;
struct UdpConn : public std::enable_shared_from_this<UdpConn>, private noncopyable {
  UdpConn() {}
  virtual ~UdpConn() { close(); }
  static UdpConnPtr createConnection(EventBase* base, const std::string& host, unsigned short port);

  template <class T>
  T& context() {
    return ctx_.context<T>();
  }

  EventBase* getBase() {
    return base_;
  }

  Channel* getChannel() {
    return channel_;
  }

  void send(Buffer msg) {
    send(msg.data(), msg.size());
msg.clear();
}
void send(const char* buf, size_t len);
void send(const std::string& s) {
send(s.data(), s.size());
}
void send(const char* s) {
send(s, strlen(s));
}
void onMsg(const UdpCallBack& cb) {
cb_ = cb;
}
void close();

std::string str() {
return peer_.toString();
}

public:
void handleRead(const UdpConnPtr&);
EventBase* base_;
Channel* channel_;
Ip4Addr local_, peer_;
AutoContext ctx_;
std::string destHost_;
int destPort_;
UdpCallback cb_; };

 

标签:std,udp,const,addr,void,send,源码,msg,handy
来源: https://www.cnblogs.com/sssblog/p/11739396.html