1 /* 2 * Copyright 2004 The WebRTC Project Authors. All rights reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #ifndef RTC_BASE_ASYNC_UDP_SOCKET_H_ 12 #define RTC_BASE_ASYNC_UDP_SOCKET_H_ 13 14 #include <stddef.h> 15 16 #include <cstdint> 17 #include <memory> 18 19 #include "absl/types/optional.h" 20 #include "api/sequence_checker.h" 21 #include "rtc_base/async_packet_socket.h" 22 #include "rtc_base/socket.h" 23 #include "rtc_base/socket_address.h" 24 #include "rtc_base/socket_factory.h" 25 #include "rtc_base/thread_annotations.h" 26 27 namespace rtc { 28 29 // Provides the ability to receive packets asynchronously. Sends are not 30 // buffered since it is acceptable to drop packets under high load. 31 class AsyncUDPSocket : public AsyncPacketSocket { 32 public: 33 // Binds `socket` and creates AsyncUDPSocket for it. Takes ownership 34 // of `socket`. Returns null if bind() fails (`socket` is destroyed 35 // in that case). 36 static AsyncUDPSocket* Create(Socket* socket, 37 const SocketAddress& bind_address); 38 // Creates a new socket for sending asynchronous UDP packets using an 39 // asynchronous socket from the given factory. 40 static AsyncUDPSocket* Create(SocketFactory* factory, 41 const SocketAddress& bind_address); 42 explicit AsyncUDPSocket(Socket* socket); 43 ~AsyncUDPSocket() = default; 44 45 SocketAddress GetLocalAddress() const override; 46 SocketAddress GetRemoteAddress() const override; 47 int Send(const void* pv, 48 size_t cb, 49 const rtc::PacketOptions& options) override; 50 int SendTo(const void* pv, 51 size_t cb, 52 const SocketAddress& addr, 53 const rtc::PacketOptions& options) override; 54 int Close() override; 55 56 State GetState() const override; 57 int GetOption(Socket::Option opt, int* value) override; 58 int SetOption(Socket::Option opt, int value) override; 59 int GetError() const override; 60 void SetError(int error) override; 61 62 private: 63 // Called when the underlying socket is ready to be read from. 64 void OnReadEvent(Socket* socket); 65 // Called when the underlying socket is ready to send. 66 void OnWriteEvent(Socket* socket); 67 68 RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker sequence_checker_; 69 std::unique_ptr<Socket> socket_; 70 static constexpr int BUF_SIZE = 64 * 1024; 71 char buf_[BUF_SIZE] RTC_GUARDED_BY(sequence_checker_); 72 absl::optional<int64_t> socket_time_offset_ RTC_GUARDED_BY(sequence_checker_); 73 }; 74 75 } // namespace rtc 76 77 #endif // RTC_BASE_ASYNC_UDP_SOCKET_H_ 78