test_echo_server.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #ifndef RTC_BASE_TEST_ECHO_SERVER_H_
  11. #define RTC_BASE_TEST_ECHO_SERVER_H_
  12. #include <stddef.h>
  13. #include <stdint.h>
  14. #include <list>
  15. #include <memory>
  16. #include "absl/algorithm/container.h"
  17. #include "rtc_base/async_packet_socket.h"
  18. #include "rtc_base/async_socket.h"
  19. #include "rtc_base/async_tcp_socket.h"
  20. #include "rtc_base/constructor_magic.h"
  21. #include "rtc_base/socket_address.h"
  22. #include "rtc_base/third_party/sigslot/sigslot.h"
  23. #include "rtc_base/thread.h"
  24. namespace rtc {
  25. // A test echo server, echoes back any packets sent to it.
  26. // Useful for unit tests.
  27. class TestEchoServer : public sigslot::has_slots<> {
  28. public:
  29. TestEchoServer(Thread* thread, const SocketAddress& addr);
  30. ~TestEchoServer() override;
  31. SocketAddress address() const { return server_socket_->GetLocalAddress(); }
  32. private:
  33. void OnAccept(AsyncSocket* socket) {
  34. AsyncSocket* raw_socket = socket->Accept(nullptr);
  35. if (raw_socket) {
  36. AsyncTCPSocket* packet_socket = new AsyncTCPSocket(raw_socket, false);
  37. packet_socket->SignalReadPacket.connect(this, &TestEchoServer::OnPacket);
  38. packet_socket->SignalClose.connect(this, &TestEchoServer::OnClose);
  39. client_sockets_.push_back(packet_socket);
  40. }
  41. }
  42. void OnPacket(AsyncPacketSocket* socket,
  43. const char* buf,
  44. size_t size,
  45. const SocketAddress& remote_addr,
  46. const int64_t& /* packet_time_us */) {
  47. rtc::PacketOptions options;
  48. socket->Send(buf, size, options);
  49. }
  50. void OnClose(AsyncPacketSocket* socket, int err) {
  51. ClientList::iterator it = absl::c_find(client_sockets_, socket);
  52. client_sockets_.erase(it);
  53. Thread::Current()->Dispose(socket);
  54. }
  55. typedef std::list<AsyncTCPSocket*> ClientList;
  56. std::unique_ptr<AsyncSocket> server_socket_;
  57. ClientList client_sockets_;
  58. RTC_DISALLOW_COPY_AND_ASSIGN(TestEchoServer);
  59. };
  60. } // namespace rtc
  61. #endif // RTC_BASE_TEST_ECHO_SERVER_H_