peerconnection_server 解析
WebRTC windows example下的peerconnection_server
SocketBase 为windows socket的封装类;
class SocketBase { public: SocketBase() : socket_(INVALID_SOCKET) {} explicit SocketBase(NativeSocket socket) : socket_(socket) {} ~SocketBase() { Close(); } NativeSocket socket() const { return socket_; } bool valid() const { return socket_ != INVALID_SOCKET; } bool Create(); void Close(); protected: NativeSocket socket_; };
Create 方法会创建一个TCP socket
bool SocketBase::Create() { assert(!valid()); socket_ = ::socket(AF_INET, SOCK_STREAM, 0); return valid(); }
ListeningSocket是server socket,用于侦听端口和接收客户端请求;
class ListeningSocket : public SocketBase { public: ListeningSocket() {} bool Listen(unsigned short port); DataSocket* Accept() const; };
Accept方法为每个新连接产生一个DataSocket实例;
DataSocket* ListeningSocket::Accept() const { assert(valid()); struct sockaddr_in addr = {0}; socklen_t size = sizeof(addr); NativeSocket client = accept(socket_, reinterpret_cast<sockaddr*>(&addr), &size); if (client == INVALID_SOCKET) return NULL; return new DataSocket(client); }
class DataSocket : public SocketBase { public:
bool OnDataAvailable(bool* close_socket); // Send a raw buffer of bytes. bool Send(const std::string& data) const;
// Send an HTTP response. bool Send(const std::string& status, bool connection_close, const std::string& content_type, const std::string& extra_headers, const std::string& data) const; ... };