1#pragma once 2#include "Common.h" 3 4#include <utility> // swap 5#include <netinet/in.h> 6 7class InetAddress; 8 9// RAII handle for socket fd 10class Socket : noncopyable 11{ 12 public: 13 explicit Socket(int sockfd); 14 ~Socket(); // close sockfd_ 15 16 Socket(Socket&& rhs) 17 : Socket(rhs.sockfd_) 18 { 19 rhs.sockfd_ = -1; 20 } 21 22 Socket& operator=(Socket&& rhs) 23 { 24 swap(rhs); 25 return *this; 26 } 27 28 void swap(Socket& rhs) 29 { 30 std::swap(sockfd_, rhs.sockfd_); 31 } 32 33 int fd() { return sockfd_; } 34 35 // Sockets API 36 void bindOrDie(const InetAddress& addr); 37 void listenOrDie(); 38 // return 0 on success 39 int connect(const InetAddress& addr); 40 void shutdownWrite(); 41 42 void setReuseAddr(bool on); 43 void setTcpNoDelay(bool on); 44 45 InetAddress getLocalAddr() const; 46 InetAddress getPeerAddr() const; 47 48 int recv(void* buf, int len); 49 int send(const void* buf, int len); 50 51 // factory methods 52 static Socket createTCP(sa_family_t family); // AF_INET or AF_INET6 53 static Socket createUDP(sa_family_t family); // AF_INET or AF_INET6 54 55 private: 56 int sockfd_; 57}; 58