2
0
Murat Dogan 4 жил өмнө
parent
commit
895fe88a62

+ 74 - 0
.vscode/settings.json

@@ -0,0 +1,74 @@
+{
+    "files.associations": {
+        "iostream": "cpp",
+        "cctype": "cpp",
+        "clocale": "cpp",
+        "cmath": "cpp",
+        "csignal": "cpp",
+        "cstdarg": "cpp",
+        "cstddef": "cpp",
+        "cstdio": "cpp",
+        "cstdlib": "cpp",
+        "cstring": "cpp",
+        "ctime": "cpp",
+        "cwchar": "cpp",
+        "cwctype": "cpp",
+        "array": "cpp",
+        "atomic": "cpp",
+        "strstream": "cpp",
+        "bit": "cpp",
+        "*.tcc": "cpp",
+        "bitset": "cpp",
+        "chrono": "cpp",
+        "codecvt": "cpp",
+        "complex": "cpp",
+        "condition_variable": "cpp",
+        "cstdint": "cpp",
+        "deque": "cpp",
+        "forward_list": "cpp",
+        "list": "cpp",
+        "map": "cpp",
+        "set": "cpp",
+        "unordered_map": "cpp",
+        "unordered_set": "cpp",
+        "vector": "cpp",
+        "exception": "cpp",
+        "algorithm": "cpp",
+        "functional": "cpp",
+        "iterator": "cpp",
+        "memory": "cpp",
+        "memory_resource": "cpp",
+        "numeric": "cpp",
+        "optional": "cpp",
+        "random": "cpp",
+        "ratio": "cpp",
+        "regex": "cpp",
+        "string": "cpp",
+        "string_view": "cpp",
+        "system_error": "cpp",
+        "tuple": "cpp",
+        "type_traits": "cpp",
+        "utility": "cpp",
+        "fstream": "cpp",
+        "future": "cpp",
+        "initializer_list": "cpp",
+        "iomanip": "cpp",
+        "iosfwd": "cpp",
+        "istream": "cpp",
+        "limits": "cpp",
+        "mutex": "cpp",
+        "new": "cpp",
+        "ostream": "cpp",
+        "shared_mutex": "cpp",
+        "sstream": "cpp",
+        "stdexcept": "cpp",
+        "streambuf": "cpp",
+        "thread": "cpp",
+        "cfenv": "cpp",
+        "cinttypes": "cpp",
+        "typeindex": "cpp",
+        "typeinfo": "cpp",
+        "valarray": "cpp",
+        "variant": "cpp"
+    }
+}

+ 1 - 0
CMakeLists.txt

@@ -374,6 +374,7 @@ if(NOT NO_EXAMPLES AND NOT CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
 	set(JSON_BuildTests OFF CACHE INTERNAL "")
 	add_subdirectory(deps/json)
 	add_subdirectory(examples/client)
+	add_subdirectory(examples/client-benchmark)
 if(NOT NO_MEDIA)
 	add_subdirectory(examples/media)
 	add_subdirectory(examples/sfu-media)

+ 24 - 0
examples/client-benchmark/CMakeLists.txt

@@ -0,0 +1,24 @@
+cmake_minimum_required(VERSION 3.7)
+if(POLICY CMP0079)
+	cmake_policy(SET CMP0079 NEW)
+endif()
+
+if(WIN32)
+	add_executable(datachannel-client-benchmark main.cpp parse_cl.cpp parse_cl.h getopt.cpp getopt.h)
+	target_compile_definitions(datachannel-client-benchmark PUBLIC STATIC_GETOPT)
+else()
+	add_executable(datachannel-client-benchmark main.cpp parse_cl.cpp parse_cl.h)
+endif()
+
+set_target_properties(datachannel-client-benchmark PROPERTIES
+	CXX_STANDARD 17
+	OUTPUT_NAME client-benchmark)
+target_link_libraries(datachannel-client-benchmark datachannel nlohmann_json)
+
+if(WIN32)
+	add_custom_command(TARGET datachannel-client-benchmark POST_BUILD
+		COMMAND ${CMAKE_COMMAND} -E copy_if_different
+		"$<TARGET_FILE_DIR:datachannel>/datachannel.dll"
+		$<TARGET_FILE_DIR:datachannel-client-benchmark>
+	)
+endif()

+ 339 - 0
examples/client-benchmark/LICENSE

@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.

+ 513 - 0
examples/client-benchmark/getopt.cpp

@@ -0,0 +1,513 @@
+/* Getopt for Microsoft C
+This code is a modification of the Free Software Foundation, Inc.
+Getopt library for parsing command line argument the purpose was
+to provide a Microsoft Visual C friendly derivative. This code
+provides functionality for both Unicode and Multibyte builds.
+
+Date: 02/03/2011 - Ludvik Jerabek - Initial Release
+Version: 1.0
+Comment: Supports getopt, getopt_long, and getopt_long_only
+and POSIXLY_CORRECT environment flag
+License: LGPL
+
+Revisions:
+
+02/03/2011 - Ludvik Jerabek - Initial Release
+02/20/2011 - Ludvik Jerabek - Fixed compiler warnings at Level 4
+07/05/2011 - Ludvik Jerabek - Added no_argument, required_argument, optional_argument defs
+08/03/2011 - Ludvik Jerabek - Fixed non-argument runtime bug which caused runtime exception
+08/09/2011 - Ludvik Jerabek - Added code to export functions for DLL and LIB
+02/15/2012 - Ludvik Jerabek - Fixed _GETOPT_THROW definition missing in implementation file
+08/01/2012 - Ludvik Jerabek - Created separate functions for char and wchar_t characters so single dll can do both unicode and ansi
+10/15/2012 - Ludvik Jerabek - Modified to match latest GNU features
+06/19/2015 - Ludvik Jerabek - Fixed maximum option limitation caused by option_a (255) and option_w (65535) structure val variable
+24/10/2020 - Paul-Louis Ageneau - Removed Unicode version
+
+**DISCLAIMER**
+THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
+EITHER EXPRESS OR IMPLIED, INCLUDING, BUT Not LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE
+EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT
+APPLY TO YOU. IN NO EVENT WILL I BE LIABLE TO ANY PARTY FOR ANY
+DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY
+USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST
+PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON
+YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN If WE ARE
+EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+*/
+
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <malloc.h>
+#include "getopt.h"
+
+#ifdef __cplusplus
+	#define _GETOPT_THROW throw()
+#else
+	#define _GETOPT_THROW
+#endif
+
+int optind = 1;
+int opterr = 1;
+int optopt = '?';
+enum ENUM_ORDERING { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER };
+
+static struct _getopt_data_a
+{
+	int optind;
+	int opterr;
+	int optopt;
+	char *optarg;
+	int __initialized;
+	char *__nextchar;
+	enum ENUM_ORDERING __ordering;
+	int __posixly_correct;
+	int __first_nonopt;
+	int __last_nonopt;
+} getopt_data_a;
+char *optarg_a;
+
+static void exchange_a(char **argv, struct _getopt_data_a *d)
+{
+	int bottom = d->__first_nonopt;
+	int middle = d->__last_nonopt;
+	int top = d->optind;
+	char *tem;
+	while (top > middle && middle > bottom)
+	{
+		if (top - middle > middle - bottom)
+		{
+			int len = middle - bottom;
+			int i;
+			for (i = 0; i < len; i++)
+			{
+				tem = argv[bottom + i];
+				argv[bottom + i] = argv[top - (middle - bottom) + i];
+				argv[top - (middle - bottom) + i] = tem;
+			}
+			top -= len;
+		}
+		else
+		{
+			int len = top - middle;
+			int i;
+			for (i = 0; i < len; i++)
+			{
+				tem = argv[bottom + i];
+				argv[bottom + i] = argv[middle + i];
+				argv[middle + i] = tem;
+			}
+			bottom += len;
+		}
+	}
+	d->__first_nonopt += (d->optind - d->__last_nonopt);
+	d->__last_nonopt = d->optind;
+}
+static const char *_getopt_initialize_a (const char *optstring, struct _getopt_data_a *d, int posixly_correct)
+{
+	d->__first_nonopt = d->__last_nonopt = d->optind;
+	d->__nextchar = NULL;
+	d->__posixly_correct = posixly_correct | !!getenv("POSIXLY_CORRECT");
+	if (optstring[0] == '-')
+	{
+		d->__ordering = RETURN_IN_ORDER;
+		++optstring;
+	}
+	else if (optstring[0] == '+')
+	{
+		d->__ordering = REQUIRE_ORDER;
+		++optstring;
+	}
+	else if (d->__posixly_correct)
+		d->__ordering = REQUIRE_ORDER;
+	else
+		d->__ordering = PERMUTE;
+	return optstring;
+}
+int _getopt_internal_r_a (int argc, char *const *argv, const char *optstring, const struct option_a *longopts, int *longind, int long_only, struct _getopt_data_a *d, int posixly_correct)
+{
+	int print_errors = d->opterr;
+	if (argc < 1)
+		return -1;
+	d->optarg = NULL;
+	if (d->optind == 0 || !d->__initialized)
+	{
+		if (d->optind == 0)
+			d->optind = 1;
+		optstring = _getopt_initialize_a (optstring, d, posixly_correct);
+		d->__initialized = 1;
+	}
+	else if (optstring[0] == '-' || optstring[0] == '+')
+		optstring++;
+	if (optstring[0] == ':')
+		print_errors = 0;
+	if (d->__nextchar == NULL || *d->__nextchar == '\0')
+	{
+		if (d->__last_nonopt > d->optind)
+			d->__last_nonopt = d->optind;
+		if (d->__first_nonopt > d->optind)
+			d->__first_nonopt = d->optind;
+		if (d->__ordering == PERMUTE)
+		{
+			if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind)
+				exchange_a ((char **) argv, d);
+			else if (d->__last_nonopt != d->optind)
+				d->__first_nonopt = d->optind;
+			while (d->optind < argc && (argv[d->optind][0] != '-' || argv[d->optind][1] == '\0'))
+				d->optind++;
+			d->__last_nonopt = d->optind;
+		}
+		if (d->optind != argc && !strcmp(argv[d->optind], "--"))
+		{
+			d->optind++;
+			if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind)
+				exchange_a((char **) argv, d);
+			else if (d->__first_nonopt == d->__last_nonopt)
+				d->__first_nonopt = d->optind;
+			d->__last_nonopt = argc;
+			d->optind = argc;
+		}
+		if (d->optind == argc)
+		{
+			if (d->__first_nonopt != d->__last_nonopt)
+				d->optind = d->__first_nonopt;
+			return -1;
+		}
+		if ((argv[d->optind][0] != '-' || argv[d->optind][1] == '\0'))
+		{
+			if (d->__ordering == REQUIRE_ORDER)
+				return -1;
+			d->optarg = argv[d->optind++];
+			return 1;
+		}
+		d->__nextchar = (argv[d->optind] + 1 + (longopts != NULL && argv[d->optind][1] == '-'));
+	}
+	if (longopts != NULL && (argv[d->optind][1] == '-' || (long_only && (argv[d->optind][2] || !strchr(optstring, argv[d->optind][1])))))
+	{
+		char *nameend;
+		unsigned int namelen;
+		const struct option_a *p;
+		const struct option_a *pfound = NULL;
+		struct option_list
+		{
+			const struct option_a *p;
+			struct option_list *next;
+		} *ambig_list = NULL;
+		int exact = 0;
+		int indfound = -1;
+		int option_index;
+		for (nameend = d->__nextchar; *nameend && *nameend != '='; nameend++);
+		namelen = (unsigned int)(nameend - d->__nextchar);
+		for (p = longopts, option_index = 0; p->name; p++, option_index++)
+			if (!strncmp(p->name, d->__nextchar, namelen))
+			{
+				if (namelen == (unsigned int)strlen(p->name))
+				{
+					pfound = p;
+					indfound = option_index;
+					exact = 1;
+					break;
+				}
+				else if (pfound == NULL)
+				{
+					pfound = p;
+					indfound = option_index;
+				}
+				else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val)
+				{
+					struct option_list *newp = (struct option_list*)alloca(sizeof(*newp));
+					newp->p = p;
+					newp->next = ambig_list;
+					ambig_list = newp;
+				}
+			}
+			if (ambig_list != NULL && !exact)
+			{
+				if (print_errors)
+				{
+					struct option_list first;
+					first.p = pfound;
+					first.next = ambig_list;
+					ambig_list = &first;
+					fprintf (stderr, "%s: option '%s' is ambiguous; possibilities:", argv[0], argv[d->optind]);
+					do
+					{
+						fprintf (stderr, " '--%s'", ambig_list->p->name);
+						ambig_list = ambig_list->next;
+					}
+					while (ambig_list != NULL);
+					fputc ('\n', stderr);
+				}
+				d->__nextchar += strlen(d->__nextchar);
+				d->optind++;
+				d->optopt = 0;
+				return '?';
+			}
+			if (pfound != NULL)
+			{
+				option_index = indfound;
+				d->optind++;
+				if (*nameend)
+				{
+					if (pfound->has_arg)
+						d->optarg = nameend + 1;
+					else
+					{
+						if (print_errors)
+						{
+							if (argv[d->optind - 1][1] == '-')
+							{
+								fprintf(stderr, "%s: option '--%s' doesn't allow an argument\n",argv[0], pfound->name);
+							}
+							else
+							{
+								fprintf(stderr, "%s: option '%c%s' doesn't allow an argument\n",argv[0], argv[d->optind - 1][0],pfound->name);
+							}
+						}
+						d->__nextchar += strlen(d->__nextchar);
+						d->optopt = pfound->val;
+						return '?';
+					}
+				}
+				else if (pfound->has_arg == 1)
+				{
+					if (d->optind < argc)
+						d->optarg = argv[d->optind++];
+					else
+					{
+						if (print_errors)
+						{
+							fprintf(stderr,"%s: option '--%s' requires an argument\n",argv[0], pfound->name);
+						}
+						d->__nextchar += strlen(d->__nextchar);
+						d->optopt = pfound->val;
+						return optstring[0] == ':' ? ':' : '?';
+					}
+				}
+				d->__nextchar += strlen(d->__nextchar);
+				if (longind != NULL)
+					*longind = option_index;
+				if (pfound->flag)
+				{
+					*(pfound->flag) = pfound->val;
+					return 0;
+				}
+				return pfound->val;
+			}
+			if (!long_only || argv[d->optind][1] == '-' || strchr(optstring, *d->__nextchar) == NULL)
+			{
+				if (print_errors)
+				{
+					if (argv[d->optind][1] == '-')
+					{
+						fprintf(stderr, "%s: unrecognized option '--%s'\n",argv[0], d->__nextchar);
+					}
+					else
+					{
+						fprintf(stderr, "%s: unrecognized option '%c%s'\n",argv[0], argv[d->optind][0], d->__nextchar);
+					}
+				}
+				d->__nextchar = (char *)"";
+				d->optind++;
+				d->optopt = 0;
+				return '?';
+			}
+	}
+	{
+		char c = *d->__nextchar++;
+		char *temp = (char*)strchr(optstring, c);
+		if (*d->__nextchar == '\0')
+			++d->optind;
+		if (temp == NULL || c == ':' || c == ';')
+		{
+			if (print_errors)
+			{
+				fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], c);
+			}
+			d->optopt = c;
+			return '?';
+		}
+		if (temp[0] == 'W' && temp[1] == ';')
+		{
+			char *nameend;
+			const struct option_a *p;
+			const struct option_a *pfound = NULL;
+			int exact = 0;
+			int ambig = 0;
+			int indfound = 0;
+			int option_index;
+			if (longopts == NULL)
+				goto no_longs;
+			if (*d->__nextchar != '\0')
+			{
+				d->optarg = d->__nextchar;
+				d->optind++;
+			}
+			else if (d->optind == argc)
+			{
+				if (print_errors)
+				{
+					fprintf(stderr,"%s: option requires an argument -- '%c'\n",argv[0], c);
+				}
+				d->optopt = c;
+				if (optstring[0] == ':')
+					c = ':';
+				else
+					c = '?';
+				return c;
+			}
+			else
+				d->optarg = argv[d->optind++];
+			for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != '='; nameend++);
+			for (p = longopts, option_index = 0; p->name; p++, option_index++)
+				if (!strncmp(p->name, d->__nextchar, nameend - d->__nextchar))
+				{
+					if ((unsigned int) (nameend - d->__nextchar) == strlen(p->name))
+					{
+						pfound = p;
+						indfound = option_index;
+						exact = 1;
+						break;
+					}
+					else if (pfound == NULL)
+					{
+						pfound = p;
+						indfound = option_index;
+					}
+					else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val)
+						ambig = 1;
+				}
+				if (ambig && !exact)
+				{
+					if (print_errors)
+					{
+						fprintf(stderr, "%s: option '-W %s' is ambiguous\n",argv[0], d->optarg);
+					}
+					d->__nextchar += strlen(d->__nextchar);
+					d->optind++;
+					return '?';
+				}
+				if (pfound != NULL)
+				{
+					option_index = indfound;
+					if (*nameend)
+					{
+						if (pfound->has_arg)
+							d->optarg = nameend + 1;
+						else
+						{
+							if (print_errors)
+							{
+								fprintf(stderr, "%s: option '-W %s' doesn't allow an argument\n",argv[0], pfound->name);
+							}
+							d->__nextchar += strlen(d->__nextchar);
+							return '?';
+						}
+					}
+					else if (pfound->has_arg == 1)
+					{
+						if (d->optind < argc)
+							d->optarg = argv[d->optind++];
+						else
+						{
+							if (print_errors)
+							{
+								fprintf(stderr, "%s: option '-W %s' requires an argument\n",argv[0], pfound->name);
+							}
+							d->__nextchar += strlen(d->__nextchar);
+							return optstring[0] == ':' ? ':' : '?';
+						}
+					}
+					else
+						d->optarg = NULL;
+					d->__nextchar += strlen(d->__nextchar);
+					if (longind != NULL)
+						*longind = option_index;
+					if (pfound->flag)
+					{
+						*(pfound->flag) = pfound->val;
+						return 0;
+					}
+					return pfound->val;
+				}
+no_longs:
+				d->__nextchar = NULL;
+				return 'W';
+		}
+		if (temp[1] == ':')
+		{
+			if (temp[2] == ':')
+			{
+				if (*d->__nextchar != '\0')
+				{
+					d->optarg = d->__nextchar;
+					d->optind++;
+				}
+				else
+					d->optarg = NULL;
+				d->__nextchar = NULL;
+			}
+			else
+			{
+				if (*d->__nextchar != '\0')
+				{
+					d->optarg = d->__nextchar;
+					d->optind++;
+				}
+				else if (d->optind == argc)
+				{
+					if (print_errors)
+					{
+						fprintf(stderr,"%s: option requires an argument -- '%c'\n",argv[0], c);
+					}
+					d->optopt = c;
+					if (optstring[0] == ':')
+						c = ':';
+					else
+						c = '?';
+				}
+				else
+					d->optarg = argv[d->optind++];
+				d->__nextchar = NULL;
+			}
+		}
+		return c;
+	}
+}
+int _getopt_internal_a (int argc, char *const *argv, const char *optstring, const struct option_a *longopts, int *longind, int long_only, int posixly_correct)
+{
+	int result;
+	getopt_data_a.optind = optind;
+	getopt_data_a.opterr = opterr;
+	result = _getopt_internal_r_a (argc, argv, optstring, longopts,longind, long_only, &getopt_data_a,posixly_correct);
+	optind = getopt_data_a.optind;
+	optarg_a = getopt_data_a.optarg;
+	optopt = getopt_data_a.optopt;
+	return result;
+}
+int getopt_a (int argc, char *const *argv, const char *optstring) _GETOPT_THROW
+{
+	return _getopt_internal_a (argc, argv, optstring, (const struct option_a *) 0, (int *) 0, 0, 0);
+}
+int getopt_long_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW
+{
+	return _getopt_internal_a (argc, argv, options, long_options, opt_index, 0, 0);
+}
+int getopt_long_only_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW
+{
+	return _getopt_internal_a (argc, argv, options, long_options, opt_index, 1, 0);
+}
+int _getopt_long_r_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index, struct _getopt_data_a *d)
+{
+	return _getopt_internal_r_a (argc, argv, options, long_options, opt_index,0, d, 0);
+}
+int _getopt_long_only_r_a (int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index, struct _getopt_data_a *d)
+{
+	return _getopt_internal_r_a (argc, argv, options, long_options, opt_index, 1, d, 0);
+}
+

+ 115 - 0
examples/client-benchmark/getopt.h

@@ -0,0 +1,115 @@
+/* Getopt for Microsoft C
+This code is a modification of the Free Software Foundation, Inc.
+Getopt library for parsing command line argument the purpose was
+to provide a Microsoft Visual C friendly derivative. This code
+provides functionality for both Unicode and Multibyte builds.
+
+Date: 02/03/2011 - Ludvik Jerabek - Initial Release
+Version: 1.0
+Comment: Supports getopt, getopt_long, and getopt_long_only
+and POSIXLY_CORRECT environment flag
+License: LGPL
+
+Revisions:
+
+02/03/2011 - Ludvik Jerabek - Initial Release
+02/20/2011 - Ludvik Jerabek - Fixed compiler warnings at Level 4
+07/05/2011 - Ludvik Jerabek - Added no_argument, required_argument, optional_argument defs
+08/03/2011 - Ludvik Jerabek - Fixed non-argument runtime bug which caused runtime exception
+08/09/2011 - Ludvik Jerabek - Added code to export functions for DLL and LIB
+02/15/2012 - Ludvik Jerabek - Fixed _GETOPT_THROW definition missing in implementation file
+08/01/2012 - Ludvik Jerabek - Created separate functions for char and wchar_t characters so single dll can do both unicode and ansi
+10/15/2012 - Ludvik Jerabek - Modified to match latest GNU features
+06/19/2015 - Ludvik Jerabek - Fixed maximum option limitation caused by option_a (255) and option_w (65535) structure val variable
+24/10/2020 - Paul-Louis Ageneau - Removed Unicode version
+
+**DISCLAIMER**
+THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
+EITHER EXPRESS OR IMPLIED, INCLUDING, BUT Not LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE
+EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT
+APPLY TO YOU. IN NO EVENT WILL I BE LIABLE TO ANY PARTY FOR ANY
+DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY
+USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST
+PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON
+YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN If WE ARE
+EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+*/
+#ifndef __GETOPT_H_
+	#define __GETOPT_H_
+
+	#ifdef _GETOPT_API
+		#undef _GETOPT_API
+	#endif
+
+	#if defined(EXPORTS_GETOPT) && defined(STATIC_GETOPT)
+		#error "The preprocessor definitions of EXPORTS_GETOPT and STATIC_GETOPT can only be used individually"
+	#elif defined(STATIC_GETOPT)
+		#pragma message("Warning static builds of getopt violate the Lesser GNU Public License")
+		#define _GETOPT_API
+	#elif defined(EXPORTS_GETOPT)
+		#pragma message("Exporting getopt library")
+		#define _GETOPT_API __declspec(dllexport)
+	#else
+		#pragma message("Importing getopt library")
+		#define _GETOPT_API __declspec(dllimport)
+	#endif
+
+	// Change behavior for C\C++
+	#ifdef __cplusplus
+		#define _BEGIN_EXTERN_C extern "C" {
+		#define _END_EXTERN_C }
+		#define _GETOPT_THROW throw()
+	#else
+		#define _BEGIN_EXTERN_C
+		#define _END_EXTERN_C
+		#define _GETOPT_THROW
+	#endif
+
+	// Standard GNU options
+	#define	null_argument		0	/*Argument Null*/
+	#define	no_argument			0	/*Argument Switch Only*/
+	#define required_argument	1	/*Argument Required*/
+	#define optional_argument	2	/*Argument Optional*/	
+
+	// Shorter Options
+	#define ARG_NULL	0	/*Argument Null*/
+	#define ARG_NONE	0	/*Argument Switch Only*/
+	#define ARG_REQ		1	/*Argument Required*/
+	#define ARG_OPT		2	/*Argument Optional*/
+
+	#include <string.h>
+
+_BEGIN_EXTERN_C
+
+	extern _GETOPT_API int optind;
+	extern _GETOPT_API int opterr;
+	extern _GETOPT_API int optopt;
+
+	struct option_a
+	{
+		const char* name;
+		int has_arg;
+		int *flag;
+		int val;
+	};
+	extern _GETOPT_API char *optarg_a;
+	extern _GETOPT_API int getopt_a(int argc, char *const *argv, const char *optstring) _GETOPT_THROW;
+	extern _GETOPT_API int getopt_long_a(int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW;
+	extern _GETOPT_API int getopt_long_only_a(int argc, char *const *argv, const char *options, const struct option_a *long_options, int *opt_index) _GETOPT_THROW;
+
+_END_EXTERN_C
+
+	#undef _BEGIN_EXTERN_C
+	#undef _END_EXTERN_C
+	#undef _GETOPT_THROW
+	#undef _GETOPT_API
+
+	#define getopt getopt_a
+	#define getopt_long getopt_long_a
+	#define getopt_long_only getopt_long_only_a
+	#define option option_a
+	#define optarg optarg_a
+
+#endif  // __GETOPT_H_

+ 327 - 0
examples/client-benchmark/main.cpp

@@ -0,0 +1,327 @@
+/*
+ * libdatachannel client-benchmark example
+ * Copyright (c) 2019-2020 Paul-Louis Ageneau
+ * Copyright (c) 2019 Murat Dogan
+ * Copyright (c) 2020 Will Munn
+ * Copyright (c) 2020 Nico Chatzi
+ * Copyright (c) 2020 Lara Mackey
+ * Copyright (c) 2020 Erik Cota-Robles
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "rtc/rtc.hpp"
+
+#include "parse_cl.h"
+
+#include <nlohmann/json.hpp>
+
+#include <algorithm>
+#include <future>
+#include <iostream>
+#include <memory>
+#include <random>
+#include <stdexcept>
+#include <thread>
+#include <unordered_map>
+
+using namespace rtc;
+using namespace std;
+using namespace std::chrono_literals;
+
+using json = nlohmann::json;
+
+template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
+
+unordered_map<string, shared_ptr<PeerConnection>> peerConnectionMap;
+unordered_map<string, shared_ptr<DataChannel>> dataChannelMap;
+
+string localId;
+
+shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
+                                                weak_ptr<WebSocket> wws, string id);
+string randomId(size_t length);
+
+// Benchmark
+const size_t messageSize = 65535;
+binary messageData(messageSize);
+atomic<size_t> receivedSize = 0, sentSize = 0;
+
+int main(int argc, char **argv) try {
+	Cmdline params(argc, argv);
+
+	rtc::InitLogger(LogLevel::Info);
+
+	// Benchmark - construct message to send
+	fill(messageData.begin(), messageData.end(), std::byte(0xFF));
+
+	Configuration config;
+	string stunServer = "";
+	if (params.noStun()) {
+		cout << "No STUN server is configured. Only local hosts and public IP addresses supported."
+		     << endl;
+	} else {
+		if (params.stunServer().substr(0, 5).compare("stun:") != 0) {
+			stunServer = "stun:";
+		}
+		stunServer += params.stunServer() + ":" + to_string(params.stunPort());
+		cout << "Stun server is " << stunServer << endl;
+		config.iceServers.emplace_back(stunServer);
+	}
+
+	localId = randomId(4);
+	cout << "The local ID is: " << localId << endl;
+
+	auto ws = make_shared<WebSocket>();
+
+	std::promise<void> wsPromise;
+	auto wsFuture = wsPromise.get_future();
+
+	ws->onOpen([&wsPromise]() {
+		cout << "WebSocket connected, signaling ready" << endl;
+		wsPromise.set_value();
+	});
+
+	ws->onError([&wsPromise](string s) {
+		cout << "WebSocket error" << endl;
+		wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
+	});
+
+	ws->onClosed([]() { cout << "WebSocket closed" << endl; });
+
+	ws->onMessage([&](variant<binary, string> data) {
+		if (!holds_alternative<string>(data))
+			return;
+
+		json message = json::parse(get<string>(data));
+
+		auto it = message.find("id");
+		if (it == message.end())
+			return;
+		string id = it->get<string>();
+
+		it = message.find("type");
+		if (it == message.end())
+			return;
+		string type = it->get<string>();
+
+		shared_ptr<PeerConnection> pc;
+		if (auto jt = peerConnectionMap.find(id); jt != peerConnectionMap.end()) {
+			pc = jt->second;
+		} else if (type == "offer") {
+			cout << "Answering to " + id << endl;
+			pc = createPeerConnection(config, ws, id);
+		} else {
+			return;
+		}
+
+		if (type == "offer" || type == "answer") {
+			auto sdp = message["description"].get<string>();
+			pc->setRemoteDescription(Description(sdp, type));
+		} else if (type == "candidate") {
+			auto sdp = message["candidate"].get<string>();
+			auto mid = message["mid"].get<string>();
+			pc->addRemoteCandidate(Candidate(sdp, mid));
+		}
+	});
+
+	string wsPrefix = "";
+	if (params.webSocketServer().substr(0, 5).compare("ws://") != 0) {
+		wsPrefix = "ws://";
+	}
+	const string url = wsPrefix + params.webSocketServer() + ":" +
+	                   to_string(params.webSocketPort()) + "/" + localId;
+	cout << "Url is " << url << endl;
+	ws->open(url);
+
+	cout << "Waiting for signaling to be connected..." << endl;
+	wsFuture.get();
+
+	string id;
+	cout << "Enter a remote ID to send an offer:" << endl;
+	cin >> id;
+	cin.ignore();
+	if (id.empty()) {
+		// Nothing to do
+		return 0;
+	}
+	if (id == localId) {
+		cout << "Invalid remote ID (This is my local ID). Exiting...";
+		return 0;
+	}
+
+	cout << "Offering to " + id << endl;
+	auto pc = createPeerConnection(config, ws, id);
+
+	// We are the offerer, so create a data channel to initiate the process
+	const string label = "benchmark";
+	cout << "Creating DataChannel with label \"" << label << "\"" << endl;
+	auto dc = pc->createDataChannel(label);
+
+	dc->onOpen([id, wdc = make_weak_ptr(dc)]() {
+		cout << "DataChannel from " << id << " open" << endl;
+		if (auto dcLocked = wdc.lock()) {
+			cout << "Starting benchmark test. Sending data..." << endl;
+			try {
+				while (dcLocked->bufferedAmount() == 0) {
+					dcLocked->send(messageData);
+					sentSize += messageData.size();
+				}
+			} catch (const std::exception &e) {
+				std::cout << "Send failed: " << e.what() << std::endl;
+			}
+		}
+	});
+
+	dc->onBufferedAmountLow([wdc = make_weak_ptr(dc)]() {
+		auto dcLocked = wdc.lock();
+		if (!dcLocked)
+			return;
+
+		// Continue sending
+		try {
+			while (dcLocked->isOpen() && dcLocked->bufferedAmount() == 0) {
+				dcLocked->send(messageData);
+				sentSize += messageData.size();
+			}
+		} catch (const std::exception &e) {
+			std::cout << "Send failed: " << e.what() << std::endl;
+		}
+	});
+
+	dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
+
+	dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
+		if (holds_alternative<binary>(data))
+			receivedSize += get<binary>(data).size();
+	});
+
+	dataChannelMap.emplace(id, dc);
+
+	const int duration = 20;
+	int printStatCounter = 0;
+	for (int i = 0; i < duration; ++i) {
+		this_thread::sleep_for(1000ms);
+		cout << "#" << i << " Received: " << receivedSize.load() / 1024 << " KB/s"
+		     << "   Sent: " << sentSize.load() / 1024 << " KB/s"
+		     << "   BufferSize: " << dc->bufferedAmount() << endl;
+		receivedSize = sentSize = 0;
+		printStatCounter++;
+
+		if (printStatCounter % 5 == 0) {
+			cout << "Stats# "
+			     << "Received Total: " << pc->bytesReceived() / (1024 * 1024) << " MB"
+			     << "   Sent Total: " << pc->bytesSent() / (1024 * 1024) << " MB"
+			     << "   RTT: " << pc->rtt().value_or(0ms).count() << " ms" << endl;
+			// cout << "Selected Candidates# " << endl;
+			cout << endl;
+		}
+	}
+
+	cout << "Cleaning up..." << endl;
+
+	dataChannelMap.clear();
+	peerConnectionMap.clear();
+	return 0;
+
+} catch (const std::exception &e) {
+	std::cout << "Error: " << e.what() << std::endl;
+	dataChannelMap.clear();
+	peerConnectionMap.clear();
+	return -1;
+}
+
+// Create and setup a PeerConnection
+shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
+                                                weak_ptr<WebSocket> wws, string id) {
+	auto pc = make_shared<PeerConnection>(config);
+
+	pc->onStateChange([](PeerConnection::State state) { cout << "State: " << state << endl; });
+
+	pc->onGatheringStateChange(
+	    [](PeerConnection::GatheringState state) { cout << "Gathering State: " << state << endl; });
+
+	pc->onLocalDescription([wws, id](Description description) {
+		json message = {
+		    {"id", id}, {"type", description.typeString()}, {"description", string(description)}};
+
+		if (auto ws = wws.lock())
+			ws->send(message.dump());
+	});
+
+	pc->onLocalCandidate([wws, id](Candidate candidate) {
+		json message = {{"id", id},
+		                {"type", "candidate"},
+		                {"candidate", string(candidate)},
+		                {"mid", candidate.mid()}};
+
+		if (auto ws = wws.lock())
+			ws->send(message.dump());
+	});
+
+	pc->onDataChannel([id](shared_ptr<DataChannel> dc) {
+		cout << "DataChannel from " << id << " received with label \"" << dc->label() << "\""
+		     << endl;
+
+		cout << "Starting benchmark test. Sending data..." << endl;
+		cout << "### Check other peer's screen for stats ###" << endl;
+		try {
+			while (dc->bufferedAmount() == 0) {
+				dc->send(messageData);
+				sentSize += messageData.size();
+			}
+		} catch (const std::exception &e) {
+			std::cout << "Send failed: " << e.what() << std::endl;
+		}
+
+		dc->onBufferedAmountLow([wdc = make_weak_ptr(dc)]() {
+			auto dcLocked = wdc.lock();
+			if (!dcLocked)
+				return;
+
+			// Continue sending
+			try {
+				while (dcLocked->isOpen() && dcLocked->bufferedAmount() == 0) {
+					dcLocked->send(messageData);
+					sentSize += messageData.size();
+				}
+			} catch (const std::exception &e) {
+				std::cout << "Send failed: " << e.what() << std::endl;
+			}
+		});
+
+		dc->onClosed([id]() { cout << "DataChannel from " << id << " closed" << endl; });
+
+		dc->onMessage([id, wdc = make_weak_ptr(dc)](variant<binary, string> data) {
+			if (holds_alternative<binary>(data))
+				receivedSize += get<binary>(data).size();
+		});
+
+		dataChannelMap.emplace(id, dc);
+	});
+
+	peerConnectionMap.emplace(id, pc);
+	return pc;
+};
+
+// Helper function to generate a random ID
+string randomId(size_t length) {
+	static const string characters(
+	    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
+	string id(length, '0');
+	default_random_engine rng(random_device{}());
+	uniform_int_distribution<int> dist(0, int(characters.size() - 1));
+	generate(id.begin(), id.end(), [&]() { return characters.at(dist(rng)); });
+	return id;
+}

+ 160 - 0
examples/client-benchmark/parse_cl.cpp

@@ -0,0 +1,160 @@
+/******************************************************************************
+**
+** parse_cl.cpp
+**
+** Thu Aug  6 19:42:25 2020
+** Linux 5.4.0-42-generic (#46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020) x86_64
+** cerik@Erik-VBox-Ubuntu (Erik Cota-Robles)
+**
+** Copyright (c) 2020 Erik Cota-Robles
+**
+** Definition of command line parser class
+**
+** Automatically created by genparse v0.9.3
+**
+** See http://genparse.sourceforge.net for details and updates
+**
+**
+******************************************************************************/
+
+#include <stdlib.h>
+
+#if defined(_WIN32) || defined(WIN32)
+#include "getopt.h"
+#else
+#include <getopt.h>
+#endif
+
+#include "parse_cl.h"
+
+/*----------------------------------------------------------------------------
+**
+** Cmdline::Cmdline ()
+**
+** Constructor method.
+**
+**--------------------------------------------------------------------------*/
+
+Cmdline::Cmdline (int argc, char *argv[]) // ISO C++17 not allowed: throw (std::string )
+{
+  extern char *optarg;
+  extern int optind;
+  int c;
+
+  static struct option long_options[] =
+  {
+    {"noStun", no_argument, NULL, 'n'},
+    {"stunServer", required_argument, NULL, 's'},
+    {"stunPort", required_argument, NULL, 't'},
+    {"webSocketServer", required_argument, NULL, 'w'},
+    {"webSocketPort", required_argument, NULL, 'x'},
+    {"help", no_argument, NULL, 'h'},
+    {NULL, 0, NULL, 0}
+  };
+
+  _program_name += argv[0];
+
+  /* default values */
+  _n = false;
+  _s = "stun.l.google.com";
+  _t = 19302;
+  _w = "localhost";
+  _x = 8000;
+  _h = false;
+
+  optind = 0;
+  while ((c = getopt_long (argc, argv, "s:t:w:x:enhv", long_options, &optind)) != - 1)
+    {
+      switch (c)
+        {
+        case 'n':
+          _n = true;
+          break;
+
+        case 's':
+          _s = optarg;
+          break;
+
+        case 't':
+          _t = atoi (optarg);
+          if (_t < 0)
+            {
+              std::string err;
+              err += "parameter range error: t must be >= 0";
+              throw (std::range_error(err));
+            }
+          if (_t > 65535)
+            {
+              std::string err;
+              err += "parameter range error: t must be <= 65535";
+              throw (std::range_error(err));
+            }
+          break;
+
+        case 'w':
+          _w = optarg;
+          break;
+
+        case 'x':
+          _x = atoi (optarg);
+          if (_x < 0)
+            {
+              std::string err;
+              err += "parameter range error: x must be >= 0";
+              throw (std::range_error(err));
+            }
+          if (_x > 65535)
+            {
+              std::string err;
+              err += "parameter range error: x must be <= 65535";
+              throw (std::range_error(err));
+            }
+          break;
+
+        case 'h':
+          _h = true;
+          this->usage (EXIT_SUCCESS);
+          break;
+
+        default:
+          this->usage (EXIT_FAILURE);
+
+        }
+    } /* while */
+
+  _optind = optind;
+}
+
+/*----------------------------------------------------------------------------
+**
+** Cmdline::usage () and version()
+**
+** Print out usage (or version) information, then exit.
+**
+**--------------------------------------------------------------------------*/
+
+void Cmdline::usage (int status)
+{
+  if (status != EXIT_SUCCESS)
+    std::cerr << "Try `" << _program_name << " --help' for more information.\n";
+  else
+    {
+      std::cout << "\
+usage: " << _program_name << " [ -enstwxhv ] \n\
+libdatachannel client implementing WebRTC Data Channels with WebSocket signaling\n\
+   [ -n ] [ --noStun ] (type=FLAG)\n\
+          Do NOT use a stun server (overrides -s and -t).\n\
+   [ -s ] [ --stunServer ] (type=STRING, default=stun.l.google.com)\n\
+          Stun server URL or IP address.\n\
+   [ -t ] [ --stunPort ] (type=INTEGER, range=0...65535, default=19302)\n\
+          Stun server port.\n\
+   [ -w ] [ --webSocketServer ] (type=STRING, default=localhost)\n\
+          Web socket server URL or IP address.\n\
+   [ -x ] [ --webSocketPort ] (type=INTEGER, range=0...65535, default=8000)\n\
+          Web socket server port.\n\
+   [ -h ] [ --help ] (type=FLAG)\n\
+          Display this help and exit.\n";
+    }
+  exit (status);
+}
+

+ 67 - 0
examples/client-benchmark/parse_cl.h

@@ -0,0 +1,67 @@
+/******************************************************************************
+**
+** parse_cl.h
+**
+** Thu Aug  6 19:42:25 2020
+** Linux 5.4.0-42-generic (#46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020) x86_64
+** cerik@Erik-VBox-Ubuntu (Erik Cota-Robles)
+**
+** Copyright (c) 2020 Erik Cota-Robles
+**
+** Header file for command line parser class
+**
+** Automatically created by genparse v0.9.3
+**
+** See http://genparse.sourceforge.net for details and updates
+**
+******************************************************************************/
+
+#ifndef CMDLINE_H
+#define CMDLINE_H
+
+#include <iostream>
+#include <string>
+
+/*----------------------------------------------------------------------------
+**
+** class Cmdline
+**
+** command line parser class
+**
+**--------------------------------------------------------------------------*/
+
+class Cmdline
+{
+private:
+  /* parameters */
+  bool _n;
+  std::string _s;
+  int _t;
+  std::string _w;
+  int _x;
+  bool _h;
+
+  /* other stuff to keep track of */
+  std::string _program_name;
+  int _optind;
+
+public:
+  /* constructor and destructor */
+  Cmdline (int, char **); // ISO C++17 not allowed: throw (std::string);
+  ~Cmdline (){}
+
+  /* usage function */
+  void usage (int status);
+
+  /* return next (non-option) parameter */
+  int next_param () { return _optind; }
+
+  bool noStun () const { return _n; }
+  std::string stunServer () const { return _s; }
+  int stunPort () const { return _t; }
+  std::string webSocketServer () const { return _w; }
+  int webSocketPort () const { return _x; }
+  bool h () const { return _h; }
+};
+
+#endif