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 "rtc_base/async_packet_socket.h"
22 #include "rtc_base/async_socket.h"
23 #include "rtc_base/async_tcp_socket.h"
24 #include "rtc_base/constructor_magic.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 
address()38   SocketAddress address() const { return server_socket_->GetLocalAddress(); }
39 
40  private:
OnAccept(AsyncSocket * socket)41   void OnAccept(AsyncSocket* socket) {
42     AsyncSocket* raw_socket = socket->Accept(nullptr);
43     if (raw_socket) {
44       AsyncTCPSocket* packet_socket = new AsyncTCPSocket(raw_socket, false);
45       packet_socket->SignalReadPacket.connect(this, &TestEchoServer::OnPacket);
46       packet_socket->SignalClose.connect(this, &TestEchoServer::OnClose);
47       client_sockets_.push_back(packet_socket);
48     }
49   }
OnPacket(AsyncPacketSocket * socket,const char * buf,size_t size,const SocketAddress & remote_addr,const int64_t &)50   void OnPacket(AsyncPacketSocket* socket,
51                 const char* buf,
52                 size_t size,
53                 const SocketAddress& remote_addr,
54                 const int64_t& /* packet_time_us */) {
55     rtc::PacketOptions options;
56     socket->Send(buf, size, options);
57   }
OnClose(AsyncPacketSocket * socket,int err)58   void OnClose(AsyncPacketSocket* socket, int err) {
59     ClientList::iterator it = absl::c_find(client_sockets_, socket);
60     client_sockets_.erase(it);
61     Thread::Current()->Dispose(socket);
62   }
63 
64   typedef std::list<AsyncTCPSocket*> ClientList;
65   std::unique_ptr<AsyncSocket> server_socket_;
66   ClientList client_sockets_;
67   RTC_DISALLOW_COPY_AND_ASSIGN(TestEchoServer);
68 };
69 
70 }  // namespace rtc
71 
72 #endif  // RTC_BASE_TEST_ECHO_SERVER_H_
73