blob: 5e714eb63dd30e0e69675b1e0df9fe479f2aff4a [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 }
Yves Gerey665174f2018-06-19 15:03:05 +020043 void OnPacket(AsyncPacketSocket* socket,
44 const char* buf,
45 size_t size,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020046 const SocketAddress& remote_addr,
47 const PacketTime& packet_time) {
48 rtc::PacketOptions options;
49 socket->Send(buf, size, options);
50 }
51 void OnClose(AsyncPacketSocket* socket, int err) {
52 ClientList::iterator it =
53 std::find(client_sockets_.begin(), client_sockets_.end(), socket);
54 client_sockets_.erase(it);
55 Thread::Current()->Dispose(socket);
56 }
57
58 typedef std::list<AsyncTCPSocket*> ClientList;
59 std::unique_ptr<AsyncSocket> server_socket_;
60 ClientList client_sockets_;
61 RTC_DISALLOW_COPY_AND_ASSIGN(TestEchoServer);
62};
63
64} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020066#endif // RTC_BASE_TESTECHOSERVER_H_