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_TEST_ECHO_SERVER_H_ 12 #define RTC_BASE_TEST_ECHO_SERVER_H_ 13 14 #include <stddef.h> 15 #include <stdint.h> 16 17 #include <list> 18 #include <memory> 19 20 #include "absl/algorithm/container.h" 21 #include "absl/memory/memory.h" 22 #include "rtc_base/async_packet_socket.h" 23 #include "rtc_base/async_tcp_socket.h" 24 #include "rtc_base/socket.h" 25 #include "rtc_base/socket_address.h" 26 #include "rtc_base/third_party/sigslot/sigslot.h" 27 #include "rtc_base/thread.h" 28 29 namespace rtc { 30 31 // A test echo server, echoes back any packets sent to it. 32 // Useful for unit tests. 33 class TestEchoServer : public sigslot::has_slots<> { 34 public: 35 TestEchoServer(Thread* thread, const SocketAddress& addr); 36 ~TestEchoServer() override; 37 38 TestEchoServer(const TestEchoServer&) = delete; 39 TestEchoServer& operator=(const TestEchoServer&) = delete; 40 address()41 SocketAddress address() const { return server_socket_->GetLocalAddress(); } 42 43 private: OnAccept(Socket * socket)44 void OnAccept(Socket* socket) { 45 Socket* raw_socket = socket->Accept(nullptr); 46 if (raw_socket) { 47 AsyncTCPSocket* packet_socket = new AsyncTCPSocket(raw_socket); 48 packet_socket->SignalReadPacket.connect(this, &TestEchoServer::OnPacket); 49 packet_socket->SubscribeClose( 50 this, [this](AsyncPacketSocket* s, int err) { OnClose(s, err); }); 51 client_sockets_.push_back(packet_socket); 52 } 53 } OnPacket(AsyncPacketSocket * socket,const char * buf,size_t size,const SocketAddress & remote_addr,const int64_t &)54 void OnPacket(AsyncPacketSocket* socket, 55 const char* buf, 56 size_t size, 57 const SocketAddress& remote_addr, 58 const int64_t& /* packet_time_us */) { 59 rtc::PacketOptions options; 60 socket->Send(buf, size, options); 61 } OnClose(AsyncPacketSocket * socket,int err)62 void OnClose(AsyncPacketSocket* socket, int err) { 63 ClientList::iterator it = absl::c_find(client_sockets_, socket); 64 client_sockets_.erase(it); 65 // `OnClose` is triggered by socket Close callback, deleting `socket` while 66 // processing that callback might be unsafe. 67 Thread::Current()->PostTask([socket = absl::WrapUnique(socket)] {}); 68 } 69 70 typedef std::list<AsyncTCPSocket*> ClientList; 71 std::unique_ptr<Socket> server_socket_; 72 ClientList client_sockets_; 73 }; 74 75 } // namespace rtc 76 77 #endif // RTC_BASE_TEST_ECHO_SERVER_H_ 78