blob: 672dda0f18d2893e7bb5ff549ebd501cee0bbf7e [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_TESTECHOSERVER_H_
12#define RTC_BASE_TESTECHOSERVER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <list>
15#include <memory>
Steve Anton9de3aac2017-10-24 10:08:26 -070016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "rtc_base/asynctcpsocket.h"
18#include "rtc_base/constructormagic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/socketaddress.h"
20#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020022namespace rtc {
23
24// A test echo server, echoes back any packets sent to it.
25// Useful for unit tests.
26class TestEchoServer : public sigslot::has_slots<> {
27 public:
Steve Anton9de3aac2017-10-24 10:08:26 -070028 TestEchoServer(Thread* thread, const SocketAddress& addr);
29 ~TestEchoServer() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020030
31 SocketAddress address() const { return server_socket_->GetLocalAddress(); }
32
33 private:
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 }
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 }
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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020064#endif // RTC_BASE_TESTECHOSERVER_H_