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