首页 > 其他 > 详细

handy源码阅读(六):udp类

时间:2019-10-25 18:59:36      阅读:82      评论:0      收藏:0      [点我收藏+]

分为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_; };

 

handy源码阅读(六):udp类

原文:https://www.cnblogs.com/sssblog/p/11739396.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!