mirror of
https://github.com/westonrobot/ugv_sdk
synced 2023-04-08 06:32:14 +08:00
moved asio folder and tested catkin-isolated build
This commit is contained in:
29
asio/src/Makefile.am
Normal file
29
asio/src/Makefile.am
Normal file
@@ -0,0 +1,29 @@
|
||||
if !STANDALONE
|
||||
EXAMPLES_CPP03 = examples/cpp03
|
||||
endif
|
||||
|
||||
if HAVE_CXX11
|
||||
EXAMPLES_CPP11 = examples/cpp11
|
||||
endif
|
||||
|
||||
if HAVE_CXX14
|
||||
EXAMPLES_CPP14 = examples/cpp14
|
||||
endif
|
||||
|
||||
if HAVE_CXX17
|
||||
EXAMPLES_CPP17 = examples/cpp17
|
||||
endif
|
||||
|
||||
SUBDIRS = $(EXAMPLES_CPP03) $(EXAMPLES_CPP11) $(EXAMPLES_CPP14) $(EXAMPLES_CPP17) tests
|
||||
|
||||
DIST_SUBDIRS = examples/cpp03 examples/cpp11 examples/cpp14 examples/cpp17 tests
|
||||
|
||||
EXTRA_DIST = \
|
||||
Makefile.mgw \
|
||||
Makefile.msc \
|
||||
tools/handlerlive.pl \
|
||||
tools/handlertree.pl \
|
||||
tools/handlerviz.pl
|
||||
|
||||
MAINTAINERCLEANFILES = \
|
||||
$(srcdir)/Makefile.in
|
||||
608
asio/src/Makefile.in
Normal file
608
asio/src/Makefile.in
Normal file
@@ -0,0 +1,608 @@
|
||||
# Makefile.in generated by automake 1.16.1 from Makefile.am.
|
||||
# @configure_input@
|
||||
|
||||
# Copyright (C) 1994-2018 Free Software Foundation, Inc.
|
||||
|
||||
# This Makefile.in is free software; the Free Software Foundation
|
||||
# gives unlimited permission to copy and/or distribute it,
|
||||
# with or without modifications, as long as this notice is preserved.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
|
||||
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
|
||||
# PARTICULAR PURPOSE.
|
||||
|
||||
@SET_MAKE@
|
||||
VPATH = @srcdir@
|
||||
am__is_gnu_make = { \
|
||||
if test -z '$(MAKELEVEL)'; then \
|
||||
false; \
|
||||
elif test -n '$(MAKE_HOST)'; then \
|
||||
true; \
|
||||
elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
|
||||
true; \
|
||||
else \
|
||||
false; \
|
||||
fi; \
|
||||
}
|
||||
am__make_running_with_option = \
|
||||
case $${target_option-} in \
|
||||
?) ;; \
|
||||
*) echo "am__make_running_with_option: internal error: invalid" \
|
||||
"target option '$${target_option-}' specified" >&2; \
|
||||
exit 1;; \
|
||||
esac; \
|
||||
has_opt=no; \
|
||||
sane_makeflags=$$MAKEFLAGS; \
|
||||
if $(am__is_gnu_make); then \
|
||||
sane_makeflags=$$MFLAGS; \
|
||||
else \
|
||||
case $$MAKEFLAGS in \
|
||||
*\\[\ \ ]*) \
|
||||
bs=\\; \
|
||||
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
|
||||
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
|
||||
esac; \
|
||||
fi; \
|
||||
skip_next=no; \
|
||||
strip_trailopt () \
|
||||
{ \
|
||||
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
|
||||
}; \
|
||||
for flg in $$sane_makeflags; do \
|
||||
test $$skip_next = yes && { skip_next=no; continue; }; \
|
||||
case $$flg in \
|
||||
*=*|--*) continue;; \
|
||||
-*I) strip_trailopt 'I'; skip_next=yes;; \
|
||||
-*I?*) strip_trailopt 'I';; \
|
||||
-*O) strip_trailopt 'O'; skip_next=yes;; \
|
||||
-*O?*) strip_trailopt 'O';; \
|
||||
-*l) strip_trailopt 'l'; skip_next=yes;; \
|
||||
-*l?*) strip_trailopt 'l';; \
|
||||
-[dEDm]) skip_next=yes;; \
|
||||
-[JT]) skip_next=yes;; \
|
||||
esac; \
|
||||
case $$flg in \
|
||||
*$$target_option*) has_opt=yes; break;; \
|
||||
esac; \
|
||||
done; \
|
||||
test $$has_opt = yes
|
||||
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
|
||||
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
|
||||
pkgdatadir = $(datadir)/@PACKAGE@
|
||||
pkgincludedir = $(includedir)/@PACKAGE@
|
||||
pkglibdir = $(libdir)/@PACKAGE@
|
||||
pkglibexecdir = $(libexecdir)/@PACKAGE@
|
||||
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
|
||||
install_sh_DATA = $(install_sh) -c -m 644
|
||||
install_sh_PROGRAM = $(install_sh) -c
|
||||
install_sh_SCRIPT = $(install_sh) -c
|
||||
INSTALL_HEADER = $(INSTALL_DATA)
|
||||
transform = $(program_transform_name)
|
||||
NORMAL_INSTALL = :
|
||||
PRE_INSTALL = :
|
||||
POST_INSTALL = :
|
||||
NORMAL_UNINSTALL = :
|
||||
PRE_UNINSTALL = :
|
||||
POST_UNINSTALL = :
|
||||
build_triplet = @build@
|
||||
host_triplet = @host@
|
||||
subdir = src
|
||||
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
|
||||
am__aclocal_m4_deps = $(top_srcdir)/configure.ac
|
||||
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
|
||||
$(ACLOCAL_M4)
|
||||
DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
|
||||
mkinstalldirs = $(install_sh) -d
|
||||
CONFIG_CLEAN_FILES =
|
||||
CONFIG_CLEAN_VPATH_FILES =
|
||||
AM_V_P = $(am__v_P_@AM_V@)
|
||||
am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
|
||||
am__v_P_0 = false
|
||||
am__v_P_1 = :
|
||||
AM_V_GEN = $(am__v_GEN_@AM_V@)
|
||||
am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
|
||||
am__v_GEN_0 = @echo " GEN " $@;
|
||||
am__v_GEN_1 =
|
||||
AM_V_at = $(am__v_at_@AM_V@)
|
||||
am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
|
||||
am__v_at_0 = @
|
||||
am__v_at_1 =
|
||||
SOURCES =
|
||||
DIST_SOURCES =
|
||||
RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
|
||||
ctags-recursive dvi-recursive html-recursive info-recursive \
|
||||
install-data-recursive install-dvi-recursive \
|
||||
install-exec-recursive install-html-recursive \
|
||||
install-info-recursive install-pdf-recursive \
|
||||
install-ps-recursive install-recursive installcheck-recursive \
|
||||
installdirs-recursive pdf-recursive ps-recursive \
|
||||
tags-recursive uninstall-recursive
|
||||
am__can_run_installinfo = \
|
||||
case $$AM_UPDATE_INFO_DIR in \
|
||||
n|no|NO) false;; \
|
||||
*) (install-info --version) >/dev/null 2>&1;; \
|
||||
esac
|
||||
RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \
|
||||
distclean-recursive maintainer-clean-recursive
|
||||
am__recursive_targets = \
|
||||
$(RECURSIVE_TARGETS) \
|
||||
$(RECURSIVE_CLEAN_TARGETS) \
|
||||
$(am__extra_recursive_targets)
|
||||
AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
|
||||
distdir distdir-am
|
||||
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
|
||||
# Read a list of newline-separated strings from the standard input,
|
||||
# and print each of them once, without duplicates. Input order is
|
||||
# *not* preserved.
|
||||
am__uniquify_input = $(AWK) '\
|
||||
BEGIN { nonempty = 0; } \
|
||||
{ items[$$0] = 1; nonempty = 1; } \
|
||||
END { if (nonempty) { for (i in items) print i; }; } \
|
||||
'
|
||||
# Make sure the list of sources is unique. This is necessary because,
|
||||
# e.g., the same source file might be shared among _SOURCES variables
|
||||
# for different programs/libraries.
|
||||
am__define_uniq_tagged_files = \
|
||||
list='$(am__tagged_files)'; \
|
||||
unique=`for i in $$list; do \
|
||||
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
|
||||
done | $(am__uniquify_input)`
|
||||
ETAGS = etags
|
||||
CTAGS = ctags
|
||||
am__DIST_COMMON = $(srcdir)/Makefile.in
|
||||
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
|
||||
am__relativize = \
|
||||
dir0=`pwd`; \
|
||||
sed_first='s,^\([^/]*\)/.*$$,\1,'; \
|
||||
sed_rest='s,^[^/]*/*,,'; \
|
||||
sed_last='s,^.*/\([^/]*\)$$,\1,'; \
|
||||
sed_butlast='s,/*[^/]*$$,,'; \
|
||||
while test -n "$$dir1"; do \
|
||||
first=`echo "$$dir1" | sed -e "$$sed_first"`; \
|
||||
if test "$$first" != "."; then \
|
||||
if test "$$first" = ".."; then \
|
||||
dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
|
||||
dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
|
||||
else \
|
||||
first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
|
||||
if test "$$first2" = "$$first"; then \
|
||||
dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
|
||||
else \
|
||||
dir2="../$$dir2"; \
|
||||
fi; \
|
||||
dir0="$$dir0"/"$$first"; \
|
||||
fi; \
|
||||
fi; \
|
||||
dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
|
||||
done; \
|
||||
reldir="$$dir2"
|
||||
ACLOCAL = @ACLOCAL@
|
||||
AMTAR = @AMTAR@
|
||||
AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
|
||||
AUTOCONF = @AUTOCONF@
|
||||
AUTOHEADER = @AUTOHEADER@
|
||||
AUTOMAKE = @AUTOMAKE@
|
||||
AWK = @AWK@
|
||||
CC = @CC@
|
||||
CCDEPMODE = @CCDEPMODE@
|
||||
CFLAGS = @CFLAGS@
|
||||
CPPFLAGS = @CPPFLAGS@
|
||||
CXX = @CXX@
|
||||
CXXCPP = @CXXCPP@
|
||||
CXXDEPMODE = @CXXDEPMODE@
|
||||
CXXFLAGS = @CXXFLAGS@
|
||||
CYGPATH_W = @CYGPATH_W@
|
||||
DEFS = @DEFS@
|
||||
DEPDIR = @DEPDIR@
|
||||
ECHO_C = @ECHO_C@
|
||||
ECHO_N = @ECHO_N@
|
||||
ECHO_T = @ECHO_T@
|
||||
EGREP = @EGREP@
|
||||
EXEEXT = @EXEEXT@
|
||||
GREP = @GREP@
|
||||
INSTALL = @INSTALL@
|
||||
INSTALL_DATA = @INSTALL_DATA@
|
||||
INSTALL_PROGRAM = @INSTALL_PROGRAM@
|
||||
INSTALL_SCRIPT = @INSTALL_SCRIPT@
|
||||
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
|
||||
LDFLAGS = @LDFLAGS@
|
||||
LIBOBJS = @LIBOBJS@
|
||||
LIBS = @LIBS@
|
||||
LTLIBOBJS = @LTLIBOBJS@
|
||||
MAINT = @MAINT@
|
||||
MAKEINFO = @MAKEINFO@
|
||||
MKDIR_P = @MKDIR_P@
|
||||
OBJEXT = @OBJEXT@
|
||||
PACKAGE = @PACKAGE@
|
||||
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
|
||||
PACKAGE_NAME = @PACKAGE_NAME@
|
||||
PACKAGE_STRING = @PACKAGE_STRING@
|
||||
PACKAGE_TARNAME = @PACKAGE_TARNAME@
|
||||
PACKAGE_URL = @PACKAGE_URL@
|
||||
PACKAGE_VERSION = @PACKAGE_VERSION@
|
||||
PATH_SEPARATOR = @PATH_SEPARATOR@
|
||||
RANLIB = @RANLIB@
|
||||
SET_MAKE = @SET_MAKE@
|
||||
SHELL = @SHELL@
|
||||
STRIP = @STRIP@
|
||||
VERSION = @VERSION@
|
||||
abs_builddir = @abs_builddir@
|
||||
abs_srcdir = @abs_srcdir@
|
||||
abs_top_builddir = @abs_top_builddir@
|
||||
abs_top_srcdir = @abs_top_srcdir@
|
||||
ac_ct_CC = @ac_ct_CC@
|
||||
ac_ct_CXX = @ac_ct_CXX@
|
||||
am__include = @am__include@
|
||||
am__leading_dot = @am__leading_dot@
|
||||
am__quote = @am__quote@
|
||||
am__tar = @am__tar@
|
||||
am__untar = @am__untar@
|
||||
bindir = @bindir@
|
||||
build = @build@
|
||||
build_alias = @build_alias@
|
||||
build_cpu = @build_cpu@
|
||||
build_os = @build_os@
|
||||
build_vendor = @build_vendor@
|
||||
builddir = @builddir@
|
||||
datadir = @datadir@
|
||||
datarootdir = @datarootdir@
|
||||
docdir = @docdir@
|
||||
dvidir = @dvidir@
|
||||
exec_prefix = @exec_prefix@
|
||||
host = @host@
|
||||
host_alias = @host_alias@
|
||||
host_cpu = @host_cpu@
|
||||
host_os = @host_os@
|
||||
host_vendor = @host_vendor@
|
||||
htmldir = @htmldir@
|
||||
includedir = @includedir@
|
||||
infodir = @infodir@
|
||||
install_sh = @install_sh@
|
||||
libdir = @libdir@
|
||||
libexecdir = @libexecdir@
|
||||
localedir = @localedir@
|
||||
localstatedir = @localstatedir@
|
||||
mandir = @mandir@
|
||||
mkdir_p = @mkdir_p@
|
||||
oldincludedir = @oldincludedir@
|
||||
pdfdir = @pdfdir@
|
||||
prefix = @prefix@
|
||||
program_transform_name = @program_transform_name@
|
||||
psdir = @psdir@
|
||||
sbindir = @sbindir@
|
||||
sharedstatedir = @sharedstatedir@
|
||||
srcdir = @srcdir@
|
||||
sysconfdir = @sysconfdir@
|
||||
target_alias = @target_alias@
|
||||
top_build_prefix = @top_build_prefix@
|
||||
top_builddir = @top_builddir@
|
||||
top_srcdir = @top_srcdir@
|
||||
@STANDALONE_FALSE@EXAMPLES_CPP03 = examples/cpp03
|
||||
@HAVE_CXX11_TRUE@EXAMPLES_CPP11 = examples/cpp11
|
||||
@HAVE_CXX14_TRUE@EXAMPLES_CPP14 = examples/cpp14
|
||||
@HAVE_CXX17_TRUE@EXAMPLES_CPP17 = examples/cpp17
|
||||
SUBDIRS = $(EXAMPLES_CPP03) $(EXAMPLES_CPP11) $(EXAMPLES_CPP14) $(EXAMPLES_CPP17) tests
|
||||
DIST_SUBDIRS = examples/cpp03 examples/cpp11 examples/cpp14 examples/cpp17 tests
|
||||
EXTRA_DIST = \
|
||||
Makefile.mgw \
|
||||
Makefile.msc \
|
||||
tools/handlerlive.pl \
|
||||
tools/handlertree.pl \
|
||||
tools/handlerviz.pl
|
||||
|
||||
MAINTAINERCLEANFILES = \
|
||||
$(srcdir)/Makefile.in
|
||||
|
||||
all: all-recursive
|
||||
|
||||
.SUFFIXES:
|
||||
$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps)
|
||||
@for dep in $?; do \
|
||||
case '$(am__configure_deps)' in \
|
||||
*$$dep*) \
|
||||
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
|
||||
&& { if test -f $@; then exit 0; else break; fi; }; \
|
||||
exit 1;; \
|
||||
esac; \
|
||||
done; \
|
||||
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/Makefile'; \
|
||||
$(am__cd) $(top_srcdir) && \
|
||||
$(AUTOMAKE) --foreign src/Makefile
|
||||
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
|
||||
@case '$?' in \
|
||||
*config.status*) \
|
||||
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
|
||||
*) \
|
||||
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \
|
||||
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \
|
||||
esac;
|
||||
|
||||
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
|
||||
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
|
||||
|
||||
$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
|
||||
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
|
||||
$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
|
||||
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
|
||||
$(am__aclocal_m4_deps):
|
||||
|
||||
# This directory's subdirectories are mostly independent; you can cd
|
||||
# into them and run 'make' without going through this Makefile.
|
||||
# To change the values of 'make' variables: instead of editing Makefiles,
|
||||
# (1) if the variable is set in 'config.status', edit 'config.status'
|
||||
# (which will cause the Makefiles to be regenerated when you run 'make');
|
||||
# (2) otherwise, pass the desired values on the 'make' command line.
|
||||
$(am__recursive_targets):
|
||||
@fail=; \
|
||||
if $(am__make_keepgoing); then \
|
||||
failcom='fail=yes'; \
|
||||
else \
|
||||
failcom='exit 1'; \
|
||||
fi; \
|
||||
dot_seen=no; \
|
||||
target=`echo $@ | sed s/-recursive//`; \
|
||||
case "$@" in \
|
||||
distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
|
||||
*) list='$(SUBDIRS)' ;; \
|
||||
esac; \
|
||||
for subdir in $$list; do \
|
||||
echo "Making $$target in $$subdir"; \
|
||||
if test "$$subdir" = "."; then \
|
||||
dot_seen=yes; \
|
||||
local_target="$$target-am"; \
|
||||
else \
|
||||
local_target="$$target"; \
|
||||
fi; \
|
||||
($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
|
||||
|| eval $$failcom; \
|
||||
done; \
|
||||
if test "$$dot_seen" = "no"; then \
|
||||
$(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
|
||||
fi; test -z "$$fail"
|
||||
|
||||
ID: $(am__tagged_files)
|
||||
$(am__define_uniq_tagged_files); mkid -fID $$unique
|
||||
tags: tags-recursive
|
||||
TAGS: tags
|
||||
|
||||
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
|
||||
set x; \
|
||||
here=`pwd`; \
|
||||
if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
|
||||
include_option=--etags-include; \
|
||||
empty_fix=.; \
|
||||
else \
|
||||
include_option=--include; \
|
||||
empty_fix=; \
|
||||
fi; \
|
||||
list='$(SUBDIRS)'; for subdir in $$list; do \
|
||||
if test "$$subdir" = .; then :; else \
|
||||
test ! -f $$subdir/TAGS || \
|
||||
set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
|
||||
fi; \
|
||||
done; \
|
||||
$(am__define_uniq_tagged_files); \
|
||||
shift; \
|
||||
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
|
||||
test -n "$$unique" || unique=$$empty_fix; \
|
||||
if test $$# -gt 0; then \
|
||||
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
|
||||
"$$@" $$unique; \
|
||||
else \
|
||||
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
|
||||
$$unique; \
|
||||
fi; \
|
||||
fi
|
||||
ctags: ctags-recursive
|
||||
|
||||
CTAGS: ctags
|
||||
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
|
||||
$(am__define_uniq_tagged_files); \
|
||||
test -z "$(CTAGS_ARGS)$$unique" \
|
||||
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
|
||||
$$unique
|
||||
|
||||
GTAGS:
|
||||
here=`$(am__cd) $(top_builddir) && pwd` \
|
||||
&& $(am__cd) $(top_srcdir) \
|
||||
&& gtags -i $(GTAGS_ARGS) "$$here"
|
||||
cscopelist: cscopelist-recursive
|
||||
|
||||
cscopelist-am: $(am__tagged_files)
|
||||
list='$(am__tagged_files)'; \
|
||||
case "$(srcdir)" in \
|
||||
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
|
||||
*) sdir=$(subdir)/$(srcdir) ;; \
|
||||
esac; \
|
||||
for i in $$list; do \
|
||||
if test -f "$$i"; then \
|
||||
echo "$(subdir)/$$i"; \
|
||||
else \
|
||||
echo "$$sdir/$$i"; \
|
||||
fi; \
|
||||
done >> $(top_builddir)/cscope.files
|
||||
|
||||
distclean-tags:
|
||||
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
|
||||
|
||||
distdir: $(BUILT_SOURCES)
|
||||
$(MAKE) $(AM_MAKEFLAGS) distdir-am
|
||||
|
||||
distdir-am: $(DISTFILES)
|
||||
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
|
||||
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
|
||||
list='$(DISTFILES)'; \
|
||||
dist_files=`for file in $$list; do echo $$file; done | \
|
||||
sed -e "s|^$$srcdirstrip/||;t" \
|
||||
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
|
||||
case $$dist_files in \
|
||||
*/*) $(MKDIR_P) `echo "$$dist_files" | \
|
||||
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
|
||||
sort -u` ;; \
|
||||
esac; \
|
||||
for file in $$dist_files; do \
|
||||
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
|
||||
if test -d $$d/$$file; then \
|
||||
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
|
||||
if test -d "$(distdir)/$$file"; then \
|
||||
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
|
||||
fi; \
|
||||
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
|
||||
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
|
||||
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
|
||||
fi; \
|
||||
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
|
||||
else \
|
||||
test -f "$(distdir)/$$file" \
|
||||
|| cp -p $$d/$$file "$(distdir)/$$file" \
|
||||
|| exit 1; \
|
||||
fi; \
|
||||
done
|
||||
@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
|
||||
if test "$$subdir" = .; then :; else \
|
||||
$(am__make_dryrun) \
|
||||
|| test -d "$(distdir)/$$subdir" \
|
||||
|| $(MKDIR_P) "$(distdir)/$$subdir" \
|
||||
|| exit 1; \
|
||||
dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
|
||||
$(am__relativize); \
|
||||
new_distdir=$$reldir; \
|
||||
dir1=$$subdir; dir2="$(top_distdir)"; \
|
||||
$(am__relativize); \
|
||||
new_top_distdir=$$reldir; \
|
||||
echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
|
||||
echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
|
||||
($(am__cd) $$subdir && \
|
||||
$(MAKE) $(AM_MAKEFLAGS) \
|
||||
top_distdir="$$new_top_distdir" \
|
||||
distdir="$$new_distdir" \
|
||||
am__remove_distdir=: \
|
||||
am__skip_length_check=: \
|
||||
am__skip_mode_fix=: \
|
||||
distdir) \
|
||||
|| exit 1; \
|
||||
fi; \
|
||||
done
|
||||
check-am: all-am
|
||||
check: check-recursive
|
||||
all-am: Makefile
|
||||
installdirs: installdirs-recursive
|
||||
installdirs-am:
|
||||
install: install-recursive
|
||||
install-exec: install-exec-recursive
|
||||
install-data: install-data-recursive
|
||||
uninstall: uninstall-recursive
|
||||
|
||||
install-am: all-am
|
||||
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
|
||||
|
||||
installcheck: installcheck-recursive
|
||||
install-strip:
|
||||
if test -z '$(STRIP)'; then \
|
||||
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
|
||||
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
|
||||
install; \
|
||||
else \
|
||||
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
|
||||
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
|
||||
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
|
||||
fi
|
||||
mostlyclean-generic:
|
||||
|
||||
clean-generic:
|
||||
|
||||
distclean-generic:
|
||||
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
|
||||
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
|
||||
|
||||
maintainer-clean-generic:
|
||||
@echo "This command is intended for maintainers to use"
|
||||
@echo "it deletes files that may require special tools to rebuild."
|
||||
-test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES)
|
||||
clean: clean-recursive
|
||||
|
||||
clean-am: clean-generic mostlyclean-am
|
||||
|
||||
distclean: distclean-recursive
|
||||
-rm -f Makefile
|
||||
distclean-am: clean-am distclean-generic distclean-tags
|
||||
|
||||
dvi: dvi-recursive
|
||||
|
||||
dvi-am:
|
||||
|
||||
html: html-recursive
|
||||
|
||||
html-am:
|
||||
|
||||
info: info-recursive
|
||||
|
||||
info-am:
|
||||
|
||||
install-data-am:
|
||||
|
||||
install-dvi: install-dvi-recursive
|
||||
|
||||
install-dvi-am:
|
||||
|
||||
install-exec-am:
|
||||
|
||||
install-html: install-html-recursive
|
||||
|
||||
install-html-am:
|
||||
|
||||
install-info: install-info-recursive
|
||||
|
||||
install-info-am:
|
||||
|
||||
install-man:
|
||||
|
||||
install-pdf: install-pdf-recursive
|
||||
|
||||
install-pdf-am:
|
||||
|
||||
install-ps: install-ps-recursive
|
||||
|
||||
install-ps-am:
|
||||
|
||||
installcheck-am:
|
||||
|
||||
maintainer-clean: maintainer-clean-recursive
|
||||
-rm -f Makefile
|
||||
maintainer-clean-am: distclean-am maintainer-clean-generic
|
||||
|
||||
mostlyclean: mostlyclean-recursive
|
||||
|
||||
mostlyclean-am: mostlyclean-generic
|
||||
|
||||
pdf: pdf-recursive
|
||||
|
||||
pdf-am:
|
||||
|
||||
ps: ps-recursive
|
||||
|
||||
ps-am:
|
||||
|
||||
uninstall-am:
|
||||
|
||||
.MAKE: $(am__recursive_targets) install-am install-strip
|
||||
|
||||
.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
|
||||
check-am clean clean-generic cscopelist-am ctags ctags-am \
|
||||
distclean distclean-generic distclean-tags distdir dvi dvi-am \
|
||||
html html-am info info-am install install-am install-data \
|
||||
install-data-am install-dvi install-dvi-am install-exec \
|
||||
install-exec-am install-html install-html-am install-info \
|
||||
install-info-am install-man install-pdf install-pdf-am \
|
||||
install-ps install-ps-am install-strip installcheck \
|
||||
installcheck-am installdirs installdirs-am maintainer-clean \
|
||||
maintainer-clean-generic mostlyclean mostlyclean-generic pdf \
|
||||
pdf-am ps ps-am tags tags-am uninstall uninstall-am
|
||||
|
||||
.PRECIOUS: Makefile
|
||||
|
||||
|
||||
# Tell versions [3.59,3.63) of GNU make to not export all variables.
|
||||
# Otherwise a system limit (for SysV at least) may be exceeded.
|
||||
.NOEXPORT:
|
||||
300
asio/src/Makefile.mgw
Normal file
300
asio/src/Makefile.mgw
Normal file
@@ -0,0 +1,300 @@
|
||||
SHELL=cmd
|
||||
|
||||
ifndef BOOSTDIR
|
||||
BOOSTDIR = ../../boost_1_73_0
|
||||
endif
|
||||
|
||||
ifdef OPTIMISED
|
||||
OPTIM_CXXFLAGS = -O2
|
||||
OPTIM_LDFLAGS = -O2
|
||||
else
|
||||
OPTIM_CXXFLAGS = -fno-inline
|
||||
OPTIM_LDFLAGS =
|
||||
endif
|
||||
|
||||
ifndef STANDALONE
|
||||
BOOST_CXXFLAGS = -I$(BOOSTDIR) -DASIO_ENABLE_BOOST
|
||||
endif
|
||||
|
||||
ifdef SEPARATE_COMPILATION
|
||||
SEPARATE_COMPILATION_LIB = libasio.a
|
||||
SEPARATE_COMPILATION_CXXFLAGS = \
|
||||
-DASIO_SEPARATE_COMPILATION \
|
||||
-DASIO_ENABLE_CANCELIO
|
||||
endif
|
||||
|
||||
CXXFLAGS = -g -Wall -Wextra -mthreads -I../include \
|
||||
$(OPTIM_CXXFLAGS) \
|
||||
$(BOOST_CXXFLAGS) \
|
||||
$(SEPARATE_COMPILATION_CXXFLAGS)
|
||||
LDFLAGS = -g -mthreads $(OPTIM_LDFLAGS)
|
||||
LIBS = $(SEPARATE_COMPILATION_LIB) -lws2_32 -lmswsock
|
||||
DEFINES = -D_WIN32_WINNT=0x0501
|
||||
|
||||
PERFORMANCE_TEST_EXES = \
|
||||
tests/performance/client.exe \
|
||||
tests/performance/server.exe
|
||||
|
||||
UNIT_TEST_EXES = \
|
||||
tests/unit/associated_allocator.exe \
|
||||
tests/unit/associated_executor.exe \
|
||||
tests/unit/async_result.exe \
|
||||
tests/unit/awaitable.exe \
|
||||
tests/unit/basic_datagram_socket.exe \
|
||||
tests/unit/basic_deadline_timer.exe \
|
||||
tests/unit/basic_raw_socket.exe \
|
||||
tests/unit/basic_seq_packet_socket.exe \
|
||||
tests/unit/basic_serial_port.exe \
|
||||
tests/unit/basic_signal_set.exe \
|
||||
tests/unit/basic_socket.exe \
|
||||
tests/unit/basic_socket_acceptor.exe \
|
||||
tests/unit/basic_stream_socket.exe \
|
||||
tests/unit/basic_streambuf.exe \
|
||||
tests/unit/basic_waitable_timer.exe \
|
||||
tests/unit/bind_executor.exe \
|
||||
tests/unit/buffered_read_stream.exe \
|
||||
tests/unit/buffered_stream.exe \
|
||||
tests/unit/buffered_write_stream.exe \
|
||||
tests/unit/buffer.exe \
|
||||
tests/unit/buffers_iterator.exe \
|
||||
tests/unit/co_spawn.exe \
|
||||
tests/unit/completion_condition.exe \
|
||||
tests/unit/compose.exe \
|
||||
tests/unit/connect.exe \
|
||||
tests/unit/coroutine.exe \
|
||||
tests/unit/deadline_timer.exe \
|
||||
tests/unit/defer.exe \
|
||||
tests/unit/detached.exe \
|
||||
tests/unit/dispatch.exe \
|
||||
tests/unit/error.exe \
|
||||
tests/unit/execution_context.exe \
|
||||
tests/unit/execution/any_executor.exe \
|
||||
tests/unit/execution/blocking.exe \
|
||||
tests/unit/execution/blocking_adaptation.exe \
|
||||
tests/unit/execution/bulk_execute.exe \
|
||||
tests/unit/execution/bulk_guarantee.exe \
|
||||
tests/unit/execution/connect.exe \
|
||||
tests/unit/execution/context_as.exe \
|
||||
tests/unit/execution/execute.exe \
|
||||
tests/unit/execution/executor.exe \
|
||||
tests/unit/execution/invocable_archetype.exe \
|
||||
tests/unit/execution/mapping.exe \
|
||||
tests/unit/execution/operation_state.exe \
|
||||
tests/unit/execution/outstanding_work.exe \
|
||||
tests/unit/execution/prefer_only.exe \
|
||||
tests/unit/execution/receiver.exe \
|
||||
tests/unit/execution/relationship.exe \
|
||||
tests/unit/execution/schedule.exe \
|
||||
tests/unit/execution/scheduler.exe \
|
||||
tests/unit/execution/sender.exe \
|
||||
tests/unit/execution/set_done.exe \
|
||||
tests/unit/execution/set_error.exe \
|
||||
tests/unit/execution/set_value.exe \
|
||||
tests/unit/execution/start.exe \
|
||||
tests/unit/execution/submit.exe \
|
||||
tests/unit/executor.exe \
|
||||
tests/unit/executor_work_guard.exe \
|
||||
tests/unit/generic/basic_endpoint.exe \
|
||||
tests/unit/generic/datagram_protocol.exe \
|
||||
tests/unit/generic/raw_protocol.exe \
|
||||
tests/unit/generic/seq_packet_protocol.exe \
|
||||
tests/unit/generic/stream_protocol.exe \
|
||||
tests/unit/high_resolution_timer.exe \
|
||||
tests/unit/io_context.exe \
|
||||
tests/unit/io_context_strand.exe \
|
||||
tests/unit/ip/address.exe \
|
||||
tests/unit/ip/address_v4.exe \
|
||||
tests/unit/ip/address_v4_iterator.exe \
|
||||
tests/unit/ip/address_v4_range.exe \
|
||||
tests/unit/ip/address_v6.exe \
|
||||
tests/unit/ip/address_v6_iterator.exe \
|
||||
tests/unit/ip/address_v6_range.exe \
|
||||
tests/unit/ip/basic_endpoint.exe \
|
||||
tests/unit/ip/basic_resolver.exe \
|
||||
tests/unit/ip/basic_resolver_entry.exe \
|
||||
tests/unit/ip/basic_resolver_iterator.exe \
|
||||
tests/unit/ip/basic_resolver_query.exe \
|
||||
tests/unit/ip/host_name.exe \
|
||||
tests/unit/ip/icmp.exe \
|
||||
tests/unit/ip/multicast.exe \
|
||||
tests/unit/ip/network_v4.exe \
|
||||
tests/unit/ip/network_v6.exe \
|
||||
tests/unit/ip/resolver_query_base.exe \
|
||||
tests/unit/ip/tcp.exe \
|
||||
tests/unit/ip/udp.exe \
|
||||
tests/unit/ip/unicast.exe \
|
||||
tests/unit/ip/v6_only.exe \
|
||||
tests/unit/is_read_buffered.exe \
|
||||
tests/unit/is_write_buffered.exe \
|
||||
tests/unit/packaged_task.exe \
|
||||
tests/unit/placeholders.exe \
|
||||
tests/unit/post.exe \
|
||||
tests/unit/read.exe \
|
||||
tests/unit/read_at.exe \
|
||||
tests/unit/read_until.exe \
|
||||
tests/unit/redirect_error.exe \
|
||||
tests/unit/serial_port.exe \
|
||||
tests/unit/serial_port_base.exe \
|
||||
tests/unit/signal_set.exe \
|
||||
tests/unit/socket_base.exe \
|
||||
tests/unit/static_thread_pool.exe \
|
||||
tests/unit/steady_timer.exe \
|
||||
tests/unit/strand.exe \
|
||||
tests/unit/streambuf.exe \
|
||||
tests/unit/system_context.exe \
|
||||
tests/unit/system_executor.exe \
|
||||
tests/unit/system_timer.exe \
|
||||
tests/unit/this_coro.exe \
|
||||
tests/unit/thread.exe \
|
||||
tests/unit/thread_pool.exe \
|
||||
tests/unit/time_traits.exe \
|
||||
tests/unit/ts/buffer.exe \
|
||||
tests/unit/ts/executor.exe \
|
||||
tests/unit/ts/internet.exe \
|
||||
tests/unit/ts/io_context.exe \
|
||||
tests/unit/ts/net.exe \
|
||||
tests/unit/ts/netfwd.exe \
|
||||
tests/unit/ts/socket.exe \
|
||||
tests/unit/ts/timer.exe \
|
||||
tests/unit/use_awaitable.exe \
|
||||
tests/unit/use_future.exe \
|
||||
tests/unit/uses_executor.exe \
|
||||
tests/unit/wait_traits.exe \
|
||||
tests/unit/windows/basic_object_handle.exe \
|
||||
tests/unit/windows/basic_overlapped_handle.exe \
|
||||
tests/unit/windows/basic_random_access_handle.exe \
|
||||
tests/unit/windows/basic_stream_handle.exe \
|
||||
tests/unit/windows/object_handle.exe \
|
||||
tests/unit/windows/overlapped_handle.exe \
|
||||
tests/unit/windows/overlapped_ptr.exe \
|
||||
tests/unit/windows/random_access_handle.exe \
|
||||
tests/unit/windows/stream_handle.exe \
|
||||
tests/unit/write.exe \
|
||||
tests/unit/write_at.exe
|
||||
|
||||
CPP03_EXAMPLE_EXES = \
|
||||
examples/cpp03/allocation/server.exe \
|
||||
examples/cpp03/buffers/reference_counted.exe \
|
||||
examples/cpp03/chat/chat_client.exe \
|
||||
examples/cpp03/chat/chat_server.exe \
|
||||
examples/cpp03/echo/async_tcp_echo_server.exe \
|
||||
examples/cpp03/echo/async_udp_echo_server.exe \
|
||||
examples/cpp03/echo/blocking_tcp_echo_client.exe \
|
||||
examples/cpp03/echo/blocking_tcp_echo_server.exe \
|
||||
examples/cpp03/echo/blocking_udp_echo_client.exe \
|
||||
examples/cpp03/echo/blocking_udp_echo_server.exe \
|
||||
examples/cpp03/http/client/async_client.exe \
|
||||
examples/cpp03/http/client/sync_client.exe \
|
||||
examples/cpp03/http/server/http_server.exe \
|
||||
examples/cpp03/http/server2/http_server.exe \
|
||||
examples/cpp03/http/server3/http_server.exe \
|
||||
examples/cpp03/http/server4/http_server.exe \
|
||||
examples/cpp03/icmp/ping.exe \
|
||||
examples/cpp03/invocation/prioritised_handlers.exe \
|
||||
examples/cpp03/iostreams/daytime_client.exe \
|
||||
examples/cpp03/iostreams/daytime_server.exe \
|
||||
examples/cpp03/iostreams/http_client.exe \
|
||||
examples/cpp03/multicast/receiver.exe \
|
||||
examples/cpp03/multicast/sender.exe \
|
||||
examples/cpp03/nonblocking/third_party_lib.exe \
|
||||
examples/cpp03/porthopper/client.exe \
|
||||
examples/cpp03/porthopper/server.exe \
|
||||
examples/cpp03/services/daytime_client.exe \
|
||||
examples/cpp03/socks4/sync_client.exe \
|
||||
examples/cpp03/timeouts/async_tcp_client.exe \
|
||||
examples/cpp03/timeouts/blocking_tcp_client.exe \
|
||||
examples/cpp03/timeouts/blocking_token_tcp_client.exe \
|
||||
examples/cpp03/timeouts/blocking_udp_client.exe \
|
||||
examples/cpp03/timeouts/server.exe \
|
||||
examples/cpp03/timers/time_t_timer.exe \
|
||||
examples/cpp03/tutorial/timer1/timer.exe \
|
||||
examples/cpp03/tutorial/timer2/timer.exe \
|
||||
examples/cpp03/tutorial/timer3/timer.exe \
|
||||
examples/cpp03/tutorial/timer4/timer.exe \
|
||||
examples/cpp03/tutorial/timer5/timer.exe \
|
||||
examples/cpp03/tutorial/daytime1/client.exe \
|
||||
examples/cpp03/tutorial/daytime2/server.exe \
|
||||
examples/cpp03/tutorial/daytime3/server.exe \
|
||||
examples/cpp03/tutorial/daytime4/client.exe \
|
||||
examples/cpp03/tutorial/daytime5/server.exe \
|
||||
examples/cpp03/tutorial/daytime6/server.exe \
|
||||
examples/cpp03/tutorial/daytime7/server.exe \
|
||||
examples/cpp03/windows/transmit_file.exe
|
||||
|
||||
ifdef STANDALONE
|
||||
all: \
|
||||
$(SEPARATE_COMPILATION_LIB) \
|
||||
$(UNIT_TEST_EXES)
|
||||
else
|
||||
all: \
|
||||
$(SEPARATE_COMPILATION_LIB) \
|
||||
$(PERFORMANCE_TEST_EXES) \
|
||||
$(UNIT_TEST_EXES) \
|
||||
$(EXAMPLE_EXES) \
|
||||
$(OTHER_EXAMPLE_EXES)
|
||||
endif
|
||||
|
||||
ifdef SEPARATE_COMPILATION
|
||||
libasio.a: asio.o
|
||||
ar ru libasio.a asio.o
|
||||
endif
|
||||
|
||||
check: $(UNIT_TEST_EXES) $(addprefix run.,$(UNIT_TEST_EXES))
|
||||
|
||||
$(addprefix run.,$(UNIT_TEST_EXES))::
|
||||
@echo === Running $(@:run.%=%) ===
|
||||
@$(@:run.%=%)
|
||||
@echo.
|
||||
|
||||
clean:
|
||||
-del libasio.a asio.o
|
||||
-del /q /s tests\*.exe
|
||||
-del /q /s tests\*.o
|
||||
-del /q /s examples\*.exe
|
||||
-del /q /s examples\*.o
|
||||
|
||||
$(UNIT_TEST_EXES): %.exe: %.o
|
||||
g++ -o$@ $(LDFLAGS) $< $(LIBS)
|
||||
|
||||
$(PERFORMANCE_TEST_EXES) $(EXAMPLE_EXES): %.exe: %.o
|
||||
g++ -o$@ $(LDFLAGS) $< $(LIBS)
|
||||
|
||||
examples/cpp03/http/server/http_server.exe: \
|
||||
examples/cpp03/http/server/connection.o \
|
||||
examples/cpp03/http/server/connection_manager.o \
|
||||
examples/cpp03/http/server/main.o \
|
||||
examples/cpp03/http/server/mime_types.o \
|
||||
examples/cpp03/http/server/reply.o \
|
||||
examples/cpp03/http/server/request_handler.o \
|
||||
examples/cpp03/http/server/request_parser.o \
|
||||
examples/cpp03/http/server/server.o
|
||||
g++ -o$@ $(LDFLAGS) $^ $(LIBS)
|
||||
|
||||
examples/cpp03/http/server2/http_server.exe: \
|
||||
examples/cpp03/http/server2/connection.o \
|
||||
examples/cpp03/http/server2/io_context_pool.o \
|
||||
examples/cpp03/http/server2/main.o \
|
||||
examples/cpp03/http/server2/mime_types.o \
|
||||
examples/cpp03/http/server2/reply.o \
|
||||
examples/cpp03/http/server2/request_handler.o \
|
||||
examples/cpp03/http/server2/request_parser.o \
|
||||
examples/cpp03/http/server2/server.o
|
||||
g++ -o$@ $(LDFLAGS) $^ $(LIBS)
|
||||
|
||||
examples/cpp03/http/server3/http_server.exe: \
|
||||
examples/cpp03/http/server3/connection.o \
|
||||
examples/cpp03/http/server3/main.o \
|
||||
examples/cpp03/http/server3/mime_types.o \
|
||||
examples/cpp03/http/server3/reply.o \
|
||||
examples/cpp03/http/server3/request_handler.o \
|
||||
examples/cpp03/http/server3/request_parser.o \
|
||||
examples/cpp03/http/server3/server.o
|
||||
g++ -o$@ $(LDFLAGS) $^ $(LIBS)
|
||||
|
||||
examples/cpp03/services/daytime_client.exe: \
|
||||
examples/cpp03/services/daytime_client.o \
|
||||
examples/cpp03/services/logger_service.o
|
||||
g++ -o$@ $(LDFLAGS) $^ $(LIBS)
|
||||
|
||||
.cpp.o:
|
||||
g++ -o$@ -c $(CXXFLAGS) $(DEFINES) $<
|
||||
526
asio/src/Makefile.msc
Normal file
526
asio/src/Makefile.msc
Normal file
@@ -0,0 +1,526 @@
|
||||
!ifndef BOOSTDIR
|
||||
BOOSTDIR = ../../boost_1_34_1
|
||||
!endif
|
||||
|
||||
COMMON_CXXFLAGS = -nologo -EHac -GR -I. -I../include
|
||||
|
||||
!ifdef CXXLATEST
|
||||
STD_CXXFLAGS = -std:c++latest -permissive-
|
||||
!endif
|
||||
|
||||
!ifdef WARNINGS
|
||||
WARNINGS_CXXFLAGS = -W4 -wd4512 -wd4447
|
||||
!endif
|
||||
|
||||
!ifdef STATICRTL
|
||||
! ifdef DEBUG
|
||||
DEBUG_CXXFLAGS = -Zi -MTd
|
||||
! else
|
||||
DEBUG_CXXFLAGS = -O2 -MT
|
||||
! endif
|
||||
!else
|
||||
! ifdef DEBUG
|
||||
DEBUG_CXXFLAGS = -Zi -MDd
|
||||
! else
|
||||
DEBUG_CXXFLAGS = -O2 -MD
|
||||
! endif
|
||||
!endif
|
||||
|
||||
!ifdef UNICODE
|
||||
UNICODE_CXXFLAGS = -DUNICODE -D_UNICODE
|
||||
!endif
|
||||
|
||||
!ifdef TRACKING
|
||||
TRACKING_CXXFLAGS = -DASIO_ENABLE_HANDLER_TRACKING
|
||||
!endif
|
||||
|
||||
!ifndef _WIN32_WINNT
|
||||
! ifdef STORE
|
||||
_WIN32_WINNT=0x0603
|
||||
! else
|
||||
_WIN32_WINNT=0x0601
|
||||
! endif
|
||||
!endif
|
||||
|
||||
!ifdef WIN9X
|
||||
DEFINES = \
|
||||
-DASIO_DISABLE_IOCP \
|
||||
-D_WIN32_WINNT=$(_WIN32_WINNT) \
|
||||
-DBOOST_ALL_NO_LIB \
|
||||
-DBOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING
|
||||
!else
|
||||
! ifdef STORE
|
||||
DEFINES = \
|
||||
-DWINAPI_FAMILY=WINAPI_FAMILY_PC_APP \
|
||||
-DBOOST_ALL_NO_LIB -D_WIN32_WINNT=$(_WIN32_WINNT) \
|
||||
-DUNICODE -D_UNICODE \
|
||||
-DBOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING
|
||||
! else
|
||||
! ifdef WINRT
|
||||
DEFINES = \
|
||||
-ZW -FI SDKDDKVer.h -FI winapifamily.h -DWINAPI_FAMILY=WINAPI_PARTITION_APP \
|
||||
-DBOOST_ALL_NO_LIB \
|
||||
-DBOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING
|
||||
! else
|
||||
DEFINES = \
|
||||
-D_WIN32_WINNT=$(_WIN32_WINNT) \
|
||||
-DBOOST_ALL_NO_LIB \
|
||||
-DBOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING
|
||||
! endif
|
||||
! endif
|
||||
!endif
|
||||
|
||||
!ifdef SEPARATE_COMPILATION
|
||||
LIBS = asio.lib
|
||||
SEPARATE_COMPILATION_CXXFLAGS = \
|
||||
-DASIO_SEPARATE_COMPILATION \
|
||||
-DASIO_ENABLE_CANCELIO
|
||||
!endif
|
||||
|
||||
!ifdef STANDALONE
|
||||
STANDALONE_CXXFLAGS = -DASIO_STANDALONE
|
||||
!else
|
||||
STANDALONE_CXXFLAGS = -I$(BOOSTDIR) -DASIO_ENABLE_BOOST
|
||||
!endif
|
||||
|
||||
CXXFLAGS = \
|
||||
$(COMMON_CXXFLAGS) \
|
||||
$(STD_CXXFLAGS) \
|
||||
$(WARNINGS_CXXFLAGS) \
|
||||
$(DEBUG_CXXFLAGS) \
|
||||
$(UNICODE_CXXFLAGS) \
|
||||
$(TRACKING_CXXFLAGS) \
|
||||
$(SEPARATE_COMPILATION_CXXFLAGS) \
|
||||
$(STANDALONE_CXXFLAGS)
|
||||
|
||||
!ifndef SSLDIR
|
||||
SSLDIR = ../../openssl-0.9.8g
|
||||
!endif
|
||||
|
||||
SSL_CXXFLAGS = -I$(SSLDIR)/inc32
|
||||
|
||||
SSL_LIBS = \
|
||||
$(SSLDIR)/out32/libeay32.lib \
|
||||
$(SSLDIR)/out32/ssleay32.lib \
|
||||
user32.lib advapi32.lib gdi32.lib
|
||||
|
||||
LATENCY_TEST_EXES = \
|
||||
tests\latency\tcp_client.exe \
|
||||
tests\latency\tcp_server.exe \
|
||||
tests\latency\udp_client.exe \
|
||||
tests\latency\udp_server.exe
|
||||
|
||||
PERFORMANCE_TEST_EXES = \
|
||||
tests\performance\client.exe \
|
||||
tests\performance\server.exe
|
||||
|
||||
UNIT_TEST_EXES = \
|
||||
tests\unit\associated_allocator.exe \
|
||||
tests\unit\associated_executor.exe \
|
||||
tests\unit\async_result.exe \
|
||||
tests\unit\awaitable.exe \
|
||||
tests\unit\basic_datagram_socket.exe \
|
||||
tests\unit\basic_deadline_timer.exe \
|
||||
tests\unit\basic_raw_socket.exe \
|
||||
tests\unit\basic_seq_packet_socket.exe \
|
||||
tests\unit\basic_serial_port.exe \
|
||||
tests\unit\basic_signal_set.exe \
|
||||
tests\unit\basic_socket.exe \
|
||||
tests\unit\basic_socket_acceptor.exe \
|
||||
tests\unit\basic_stream_socket.exe \
|
||||
tests\unit\basic_streambuf.exe \
|
||||
tests\unit\basic_waitable_timer.exe \
|
||||
tests\unit\bind_executor.exe \
|
||||
tests\unit\buffered_read_stream.exe \
|
||||
tests\unit\buffered_stream.exe \
|
||||
tests\unit\buffered_write_stream.exe \
|
||||
tests\unit\buffer.exe \
|
||||
tests\unit\buffers_iterator.exe \
|
||||
tests\unit\co_spawn.exe \
|
||||
tests\unit\completion_condition.exe \
|
||||
tests\unit\compose.exe \
|
||||
tests\unit\connect.exe \
|
||||
tests\unit\coroutine.exe \
|
||||
tests\unit\deadline_timer.exe \
|
||||
tests\unit\defer.exe \
|
||||
tests\unit\detached.exe \
|
||||
tests\unit\dispatch.exe \
|
||||
tests\unit\error.exe \
|
||||
tests\unit\execution_context.exe \
|
||||
tests\unit\execution\any_executor.exe \
|
||||
tests\unit\execution\blocking.exe \
|
||||
tests\unit\execution\blocking_adaptation.exe \
|
||||
tests\unit\execution\bulk_execute.exe \
|
||||
tests\unit\execution\bulk_guarantee.exe \
|
||||
tests\unit\execution\connect.exe \
|
||||
tests\unit\execution\context_as.exe \
|
||||
tests\unit\execution\execute.exe \
|
||||
tests\unit\execution\executor.exe \
|
||||
tests\unit\execution\invocable_archetype.exe \
|
||||
tests\unit\execution\mapping.exe \
|
||||
tests\unit\execution\operation_state.exe \
|
||||
tests\unit\execution\outstanding_work.exe \
|
||||
tests\unit\execution\prefer_only.exe \
|
||||
tests\unit\execution\receiver.exe \
|
||||
tests\unit\execution\relationship.exe \
|
||||
tests\unit\execution\schedule.exe \
|
||||
tests\unit\execution\scheduler.exe \
|
||||
tests\unit\execution\sender.exe \
|
||||
tests\unit\execution\set_done.exe \
|
||||
tests\unit\execution\set_error.exe \
|
||||
tests\unit\execution\set_value.exe \
|
||||
tests\unit\execution\start.exe \
|
||||
tests\unit\execution\submit.exe \
|
||||
tests\unit\executor.exe \
|
||||
tests\unit\executor_work_guard.exe \
|
||||
tests\unit\generic\basic_endpoint.exe \
|
||||
tests\unit\generic\datagram_protocol.exe \
|
||||
tests\unit\generic\raw_protocol.exe \
|
||||
tests\unit\generic\seq_packet_protocol.exe \
|
||||
tests\unit\generic\stream_protocol.exe \
|
||||
tests\unit\high_resolution_timer.exe \
|
||||
tests\unit\io_context.exe \
|
||||
tests\unit\io_context_strand.exe \
|
||||
tests\unit\ip\address.exe \
|
||||
tests\unit\ip\address_v4.exe \
|
||||
tests\unit\ip\address_v4_iterator.exe \
|
||||
tests\unit\ip\address_v4_range.exe \
|
||||
tests\unit\ip\address_v6.exe \
|
||||
tests\unit\ip\address_v6_iterator.exe \
|
||||
tests\unit\ip\address_v6_range.exe \
|
||||
tests\unit\ip\basic_endpoint.exe \
|
||||
tests\unit\ip\basic_resolver.exe \
|
||||
tests\unit\ip\basic_resolver_entry.exe \
|
||||
tests\unit\ip\basic_resolver_iterator.exe \
|
||||
tests\unit\ip\basic_resolver_query.exe \
|
||||
tests\unit\ip\host_name.exe \
|
||||
tests\unit\ip\icmp.exe \
|
||||
tests\unit\ip\multicast.exe \
|
||||
tests\unit\ip\network_v4.exe \
|
||||
tests\unit\ip\network_v6.exe \
|
||||
tests\unit\ip\resolver_query_base.exe \
|
||||
tests\unit\ip\tcp.exe \
|
||||
tests\unit\ip\udp.exe \
|
||||
tests\unit\ip\unicast.exe \
|
||||
tests\unit\ip\v6_only.exe \
|
||||
tests\unit\is_read_buffered.exe \
|
||||
tests\unit\is_write_buffered.exe \
|
||||
tests\unit\packaged_task.exe \
|
||||
tests\unit\placeholders.exe \
|
||||
tests\unit\post.exe \
|
||||
tests\unit\read.exe \
|
||||
tests\unit\read_at.exe \
|
||||
tests\unit\read_until.exe \
|
||||
tests\unit\redirect_error.exe \
|
||||
tests\unit\serial_port.exe \
|
||||
tests\unit\serial_port_base.exe \
|
||||
tests\unit\signal_set.exe \
|
||||
tests\unit\socket_base.exe \
|
||||
tests\unit\static_thread_pool.exe \
|
||||
tests\unit\steady_timer.exe \
|
||||
tests\unit\strand.exe \
|
||||
tests\unit\streambuf.exe \
|
||||
tests\unit\system_context.exe \
|
||||
tests\unit\system_executor.exe \
|
||||
tests\unit\system_timer.exe \
|
||||
tests\unit\this_coro.exe \
|
||||
tests\unit\thread.exe \
|
||||
tests\unit\thread_pool.exe \
|
||||
tests\unit\time_traits.exe \
|
||||
tests\unit\ts\buffer.exe \
|
||||
tests\unit\ts\executor.exe \
|
||||
tests\unit\ts\internet.exe \
|
||||
tests\unit\ts\io_context.exe \
|
||||
tests\unit\ts\net.exe \
|
||||
tests\unit\ts\netfwd.exe \
|
||||
tests\unit\ts\socket.exe \
|
||||
tests\unit\ts\timer.exe \
|
||||
tests\unit\use_awaitable.exe \
|
||||
tests\unit\use_future.exe \
|
||||
tests\unit\uses_executor.exe \
|
||||
tests\unit\wait_traits.exe \
|
||||
tests\unit\windows\basic_object_handle.exe \
|
||||
tests\unit\windows\basic_overlapped_handle.exe \
|
||||
tests\unit\windows\basic_random_access_handle.exe \
|
||||
tests\unit\windows\basic_stream_handle.exe \
|
||||
tests\unit\windows\object_handle.exe \
|
||||
tests\unit\windows\overlapped_handle.exe \
|
||||
tests\unit\windows\overlapped_ptr.exe \
|
||||
tests\unit\windows\random_access_handle.exe \
|
||||
tests\unit\windows\stream_handle.exe \
|
||||
tests\unit\write.exe \
|
||||
tests\unit\write_at.exe
|
||||
|
||||
CPP03_EXAMPLE_EXES = \
|
||||
examples\cpp03\allocation\server.exe \
|
||||
examples\cpp03\buffers\reference_counted.exe \
|
||||
examples\cpp03\chat\chat_client.exe \
|
||||
examples\cpp03\chat\chat_server.exe \
|
||||
examples\cpp03\echo\async_tcp_echo_server.exe \
|
||||
examples\cpp03\echo\async_udp_echo_server.exe \
|
||||
examples\cpp03\echo\blocking_tcp_echo_client.exe \
|
||||
examples\cpp03\echo\blocking_tcp_echo_server.exe \
|
||||
examples\cpp03\echo\blocking_udp_echo_client.exe \
|
||||
examples\cpp03\echo\blocking_udp_echo_server.exe \
|
||||
examples\cpp03\http\client\async_client.exe \
|
||||
examples\cpp03\http\client\sync_client.exe \
|
||||
examples\cpp03\http\server\http_server.exe \
|
||||
examples\cpp03\http\server2\http_server.exe \
|
||||
examples\cpp03\http\server3\http_server.exe \
|
||||
examples\cpp03\http\server4\http_server.exe \
|
||||
examples\cpp03\icmp\ping.exe \
|
||||
examples\cpp03\invocation\prioritised_handlers.exe \
|
||||
examples\cpp03\iostreams\daytime_client.exe \
|
||||
examples\cpp03\iostreams\daytime_server.exe \
|
||||
examples\cpp03\iostreams\http_client.exe \
|
||||
examples\cpp03\multicast\receiver.exe \
|
||||
examples\cpp03\multicast\sender.exe \
|
||||
examples\cpp03\nonblocking\third_party_lib.exe \
|
||||
examples\cpp03\porthopper\client.exe \
|
||||
examples\cpp03\porthopper\server.exe \
|
||||
examples\cpp03\services\daytime_client.exe \
|
||||
examples\cpp03\socks4\sync_client.exe \
|
||||
examples\cpp03\timeouts\async_tcp_client.exe \
|
||||
examples\cpp03\timeouts\blocking_tcp_client.exe \
|
||||
examples\cpp03\timeouts\blocking_token_tcp_client.exe \
|
||||
examples\cpp03\timeouts\blocking_udp_client.exe \
|
||||
examples\cpp03\timeouts\server.exe \
|
||||
examples\cpp03\timers\time_t_timer.exe \
|
||||
examples\cpp03\tutorial\timer1\timer.exe \
|
||||
examples\cpp03\tutorial\timer2\timer.exe \
|
||||
examples\cpp03\tutorial\timer3\timer.exe \
|
||||
examples\cpp03\tutorial\timer4\timer.exe \
|
||||
examples\cpp03\tutorial\timer5\timer.exe \
|
||||
examples\cpp03\tutorial\daytime1\client.exe \
|
||||
examples\cpp03\tutorial\daytime2\server.exe \
|
||||
examples\cpp03\tutorial\daytime3\server.exe \
|
||||
examples\cpp03\tutorial\daytime4\client.exe \
|
||||
examples\cpp03\tutorial\daytime5\server.exe \
|
||||
examples\cpp03\tutorial\daytime6\server.exe \
|
||||
examples\cpp03\tutorial\daytime7\server.exe \
|
||||
examples\cpp03\windows\transmit_file.exe
|
||||
|
||||
SSL_UNIT_TEST_EXES = \
|
||||
tests\unit\ssl\basic_context.exe \
|
||||
tests\unit\ssl\context.exe \
|
||||
tests\unit\ssl\context_base.exe \
|
||||
tests\unit\ssl\context_service.exe \
|
||||
tests\unit\ssl\rfc2818_verification.exe \
|
||||
tests\unit\ssl\stream.exe \
|
||||
tests\unit\ssl\stream_base.exe \
|
||||
tests\unit\ssl\stream_service.exe
|
||||
|
||||
SSL_EXAMPLE_EXES = \
|
||||
examples\cpp03\ssl\client.exe \
|
||||
examples\cpp03\ssl\server.exe
|
||||
|
||||
!ifdef SEPARATE_COMPILATION
|
||||
all: asio.lib
|
||||
asio.lib: asio.cpp
|
||||
cl -Fe$@ -Foasio.obj $(CXXFLAGS) $(DEFINES) -c asio.cpp
|
||||
lib -name:asio.lib asio.obj
|
||||
!endif
|
||||
|
||||
!ifdef STANDALONE
|
||||
all: \
|
||||
$(UNIT_TEST_EXES)
|
||||
!else
|
||||
all: \
|
||||
$(LATENCY_TEST_EXES) \
|
||||
$(PERFORMANCE_TEST_EXES) \
|
||||
$(UNIT_TEST_EXES) \
|
||||
$(CPP03_EXAMPLE_EXES)
|
||||
!endif
|
||||
|
||||
ssl: \
|
||||
$(SSL_UNIT_TEST_EXES) \
|
||||
$(SSL_EXAMPLE_EXES)
|
||||
|
||||
check: $(UNIT_TEST_EXES)
|
||||
!@echo === Running $** === && $** && echo.
|
||||
|
||||
{tests\latency}.cpp{tests\latency}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\performance}.cpp{tests\performance}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
tests\unit\unit_test.obj: tests\unit\unit_test.cpp
|
||||
cl -Fe$@ -Fotests\unit\unit_test.obj $(CXXFLAGS) $(DEFINES) -c tests\unit\unit_test.cpp
|
||||
|
||||
{tests\unit}.cpp{tests\unit}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\unit\execution}.cpp{tests\unit\execution}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\unit\generic}.cpp{tests\unit\generic}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\unit\ip}.cpp{tests\unit\ip}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\unit\ssl}.cpp{tests\unit\ssl}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(SSL_CXXFLAGS) $(DEFINES) $< $(SSL_LIBS) $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\unit\ts}.cpp{tests\unit\ts}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{tests\unit\windows}.cpp{tests\unit\windows}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\allocation}.cpp{examples\cpp03\allocation}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\buffers}.cpp{examples\cpp03\buffers}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\chat}.cpp{examples\cpp03\chat}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\echo}.cpp{examples\cpp03\echo}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\http\client}.cpp{examples\cpp03\http\client}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\icmp}.cpp{examples\cpp03\icmp}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\invocation}.cpp{examples\cpp03\invocation}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\iostreams}.cpp{examples\cpp03\iostreams}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\multicast}.cpp{examples\cpp03\multicast}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\nonblocking}.cpp{examples\cpp03\nonblocking}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\porthopper}.cpp{examples\cpp03\porthopper}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\socks4}.cpp{examples\cpp03\socks4}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\ssl}.cpp{examples\cpp03\ssl}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(SSL_CXXFLAGS) $(DEFINES) $< $(SSL_LIBS) $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\timeouts}.cpp{examples\cpp03\timeouts}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\timers}.cpp{examples\cpp03\timers}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\timer1}.cpp{examples\cpp03\tutorial\timer1}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\timer2}.cpp{examples\cpp03\tutorial\timer2}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\timer3}.cpp{examples\cpp03\tutorial\timer3}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\timer4}.cpp{examples\cpp03\tutorial\timer4}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\timer5}.cpp{examples\cpp03\tutorial\timer5}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime1}.cpp{examples\cpp03\tutorial\daytime1}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime2}.cpp{examples\cpp03\tutorial\daytime2}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime3}.cpp{examples\cpp03\tutorial\daytime3}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime4}.cpp{examples\cpp03\tutorial\daytime4}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime5}.cpp{examples\cpp03\tutorial\daytime5}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime6}.cpp{examples\cpp03\tutorial\daytime6}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\tutorial\daytime7}.cpp{examples\cpp03\tutorial\daytime7}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp03\windows}.cpp{examples\cpp03\windows}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp11\executors}.cpp{examples\cpp11\executors}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp11\operations}.cpp{examples\cpp11\operations}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
{examples\cpp14\operations}.cpp{examples\cpp14\operations}.exe:
|
||||
cl -Fe$@ -Fo$(<:.cpp=.obj) $(CXXFLAGS) $(DEFINES) $< $(LIBS) -link -opt:ref
|
||||
|
||||
examples\cpp03\http\server\http_server.exe: \
|
||||
examples\cpp03\http\server\connection.cpp \
|
||||
examples\cpp03\http\server\connection_manager.cpp \
|
||||
examples\cpp03\http\server\main.cpp \
|
||||
examples\cpp03\http\server\mime_types.cpp \
|
||||
examples\cpp03\http\server\reply.cpp \
|
||||
examples\cpp03\http\server\request_handler.cpp \
|
||||
examples\cpp03\http\server\request_parser.cpp \
|
||||
examples\cpp03\http\server\server.cpp
|
||||
cl -Fe$@ -Foexamples\cpp03\http\server\ $(CXXFLAGS) $(DEFINES) $** $(LIBS) -link -opt:ref
|
||||
|
||||
examples\cpp03\http\server2\http_server.exe: \
|
||||
examples\cpp03\http\server2\connection.cpp \
|
||||
examples\cpp03\http\server2\io_context_pool.cpp \
|
||||
examples\cpp03\http\server2\main.cpp \
|
||||
examples\cpp03\http\server2\mime_types.cpp \
|
||||
examples\cpp03\http\server2\reply.cpp \
|
||||
examples\cpp03\http\server2\request_handler.cpp \
|
||||
examples\cpp03\http\server2\request_parser.cpp \
|
||||
examples\cpp03\http\server2\server.cpp
|
||||
cl -Fe$@ -Foexamples\cpp03\http\server2\ $(CXXFLAGS) $(DEFINES) $** $(LIBS) -link -opt:ref
|
||||
|
||||
examples\cpp03\http\server3\http_server.exe: \
|
||||
examples\cpp03\http\server3\connection.cpp \
|
||||
examples\cpp03\http\server3\main.cpp \
|
||||
examples\cpp03\http\server3\mime_types.cpp \
|
||||
examples\cpp03\http\server3\reply.cpp \
|
||||
examples\cpp03\http\server3\request_handler.cpp \
|
||||
examples\cpp03\http\server3\request_parser.cpp \
|
||||
examples\cpp03\http\server3\server.cpp
|
||||
cl -Fe$@ -Foexamples\cpp03\http\server3\ $(CXXFLAGS) $(DEFINES) $** $(LIBS) -link -opt:ref
|
||||
|
||||
examples\cpp03\http\server4\http_server.exe: \
|
||||
examples\cpp03\http\server4\file_handler.cpp \
|
||||
examples\cpp03\http\server4\main.cpp \
|
||||
examples\cpp03\http\server4\mime_types.cpp \
|
||||
examples\cpp03\http\server4\reply.cpp \
|
||||
examples\cpp03\http\server4\request_parser.cpp \
|
||||
examples\cpp03\http\server4\server.cpp
|
||||
cl -Fe$@ -Foexamples\cpp03\http\server4\ $(CXXFLAGS) $(DEFINES) $** $(LIBS) -link -opt:ref
|
||||
|
||||
examples\cpp03\services\daytime_client.exe: \
|
||||
examples\cpp03\services\daytime_client.cpp \
|
||||
examples\cpp03\services\logger_service.cpp
|
||||
cl -Fe$@ -Foexamples\cpp03\services\ $(CXXFLAGS) $(DEFINES) $** $(LIBS) -link -opt:ref
|
||||
|
||||
clean:
|
||||
-del /q /s asio.lib
|
||||
-del /q /s asio.obj
|
||||
-del /q /s tests\*.exe
|
||||
-del /q /s tests\*.exe.manifest
|
||||
-del /q /s tests\*.exp
|
||||
-del /q /s tests\*.ilk
|
||||
-del /q /s tests\*.pdb
|
||||
-del /q /s tests\*.obj
|
||||
-del /q /s examples\*.exe
|
||||
-del /q /s examples\*.exe.manifest
|
||||
-del /q /s examples\*.exp
|
||||
-del /q /s examples\*.ilk
|
||||
-del /q /s examples\*.pdb
|
||||
-del /q /s examples\*.obj
|
||||
-del /q /s *.pdb
|
||||
11
asio/src/asio.cpp
Normal file
11
asio/src/asio.cpp
Normal file
@@ -0,0 +1,11 @@
|
||||
//
|
||||
// asio.cpp
|
||||
// ~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "asio/impl/src.hpp"
|
||||
11
asio/src/asio_ssl.cpp
Normal file
11
asio/src/asio_ssl.cpp
Normal file
@@ -0,0 +1,11 @@
|
||||
//
|
||||
// asio_ssl.cpp
|
||||
// ~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "asio/ssl/impl/src.hpp"
|
||||
251
asio/src/examples/cpp03/Makefile.am
Normal file
251
asio/src/examples/cpp03/Makefile.am
Normal file
@@ -0,0 +1,251 @@
|
||||
AUTOMAKE_OPTIONS = subdir-objects
|
||||
|
||||
if SEPARATE_COMPILATION
|
||||
noinst_LIBRARIES = libasio.a
|
||||
libasio_a_SOURCES = ../../asio.cpp
|
||||
if HAVE_OPENSSL
|
||||
libasio_a_SOURCES += ../../asio_ssl.cpp
|
||||
endif
|
||||
LDADD = libasio.a
|
||||
endif
|
||||
|
||||
noinst_PROGRAMS = \
|
||||
allocation/server \
|
||||
buffers/reference_counted \
|
||||
chat/chat_client \
|
||||
chat/chat_server \
|
||||
echo/async_tcp_echo_server \
|
||||
echo/async_udp_echo_server \
|
||||
echo/blocking_tcp_echo_client \
|
||||
echo/blocking_tcp_echo_server \
|
||||
echo/blocking_udp_echo_client \
|
||||
echo/blocking_udp_echo_server \
|
||||
http/client/async_client \
|
||||
http/client/sync_client \
|
||||
http/server/http_server \
|
||||
http/server2/http_server \
|
||||
http/server3/http_server \
|
||||
http/server4/http_server \
|
||||
icmp/ping \
|
||||
invocation/prioritised_handlers \
|
||||
iostreams/daytime_client \
|
||||
iostreams/daytime_server \
|
||||
iostreams/http_client \
|
||||
multicast/receiver \
|
||||
multicast/sender \
|
||||
nonblocking/third_party_lib \
|
||||
porthopper/client \
|
||||
porthopper/server \
|
||||
services/daytime_client \
|
||||
socks4/sync_client \
|
||||
timeouts/async_tcp_client \
|
||||
timeouts/blocking_tcp_client \
|
||||
timeouts/blocking_token_tcp_client \
|
||||
timeouts/blocking_udp_client \
|
||||
timeouts/server \
|
||||
timers/time_t_timer \
|
||||
tutorial/timer1/timer \
|
||||
tutorial/timer2/timer \
|
||||
tutorial/timer3/timer \
|
||||
tutorial/timer4/timer \
|
||||
tutorial/timer5/timer \
|
||||
tutorial/daytime1/client \
|
||||
tutorial/daytime2/server \
|
||||
tutorial/daytime3/server \
|
||||
tutorial/daytime4/client \
|
||||
tutorial/daytime5/server \
|
||||
tutorial/daytime6/server \
|
||||
tutorial/daytime7/server
|
||||
|
||||
if !WINDOWS_TARGET
|
||||
noinst_PROGRAMS += \
|
||||
chat/posix_chat_client \
|
||||
fork/daemon \
|
||||
fork/process_per_connection \
|
||||
local/connect_pair \
|
||||
local/iostream_client \
|
||||
local/stream_server \
|
||||
local/stream_client
|
||||
endif
|
||||
|
||||
if WINDOWS_TARGET
|
||||
noinst_PROGRAMS += \
|
||||
windows/transmit_file
|
||||
endif
|
||||
|
||||
if HAVE_OPENSSL
|
||||
noinst_PROGRAMS += \
|
||||
ssl/client \
|
||||
ssl/server
|
||||
endif
|
||||
|
||||
if HAVE_BOOST_COROUTINE
|
||||
noinst_PROGRAMS += \
|
||||
spawn/echo_server \
|
||||
spawn/parallel_grep
|
||||
endif
|
||||
|
||||
noinst_HEADERS = \
|
||||
chat/chat_message.hpp \
|
||||
services/basic_logger.hpp \
|
||||
services/logger.hpp \
|
||||
services/logger_service.hpp
|
||||
|
||||
AM_CXXFLAGS = -I$(srcdir)/../../../include
|
||||
|
||||
allocation_server_SOURCES = allocation/server.cpp
|
||||
buffers_reference_counted_SOURCES = buffers/reference_counted.cpp
|
||||
chat_chat_client_SOURCES = chat/chat_client.cpp
|
||||
chat_chat_server_SOURCES = chat/chat_server.cpp
|
||||
echo_async_tcp_echo_server_SOURCES = echo/async_tcp_echo_server.cpp
|
||||
echo_async_udp_echo_server_SOURCES = echo/async_udp_echo_server.cpp
|
||||
echo_blocking_tcp_echo_client_SOURCES = echo/blocking_tcp_echo_client.cpp
|
||||
echo_blocking_tcp_echo_server_SOURCES = echo/blocking_tcp_echo_server.cpp
|
||||
echo_blocking_udp_echo_client_SOURCES = echo/blocking_udp_echo_client.cpp
|
||||
echo_blocking_udp_echo_server_SOURCES = echo/blocking_udp_echo_server.cpp
|
||||
http_client_async_client_SOURCES = http/client/async_client.cpp
|
||||
http_client_sync_client_SOURCES = http/client/sync_client.cpp
|
||||
http_server_http_server_SOURCES = \
|
||||
http/server/connection.cpp \
|
||||
http/server/connection_manager.cpp \
|
||||
http/server/main.cpp \
|
||||
http/server/mime_types.cpp \
|
||||
http/server/reply.cpp \
|
||||
http/server/request_handler.cpp \
|
||||
http/server/request_parser.cpp \
|
||||
http/server/server.cpp
|
||||
http_server2_http_server_SOURCES = \
|
||||
http/server2/connection.cpp \
|
||||
http/server2/io_context_pool.cpp \
|
||||
http/server2/main.cpp \
|
||||
http/server2/mime_types.cpp \
|
||||
http/server2/reply.cpp \
|
||||
http/server2/request_handler.cpp \
|
||||
http/server2/request_parser.cpp \
|
||||
http/server2/server.cpp
|
||||
http_server3_http_server_SOURCES = \
|
||||
http/server3/connection.cpp \
|
||||
http/server3/main.cpp \
|
||||
http/server3/mime_types.cpp \
|
||||
http/server3/reply.cpp \
|
||||
http/server3/request_handler.cpp \
|
||||
http/server3/request_parser.cpp \
|
||||
http/server3/server.cpp
|
||||
http_server4_http_server_SOURCES = \
|
||||
http/server4/file_handler.cpp \
|
||||
http/server4/main.cpp \
|
||||
http/server4/mime_types.cpp \
|
||||
http/server4/reply.cpp \
|
||||
http/server4/request_parser.cpp \
|
||||
http/server4/server.cpp
|
||||
icmp_ping_SOURCES = icmp/ping.cpp
|
||||
invocation_prioritised_handlers_SOURCES = invocation/prioritised_handlers.cpp
|
||||
iostreams_daytime_client_SOURCES = iostreams/daytime_client.cpp
|
||||
iostreams_daytime_server_SOURCES = iostreams/daytime_server.cpp
|
||||
iostreams_http_client_SOURCES = iostreams/http_client.cpp
|
||||
multicast_receiver_SOURCES = multicast/receiver.cpp
|
||||
multicast_sender_SOURCES = multicast/sender.cpp
|
||||
nonblocking_third_party_lib_SOURCES = nonblocking/third_party_lib.cpp
|
||||
porthopper_client_SOURCES = porthopper/client.cpp
|
||||
porthopper_server_SOURCES = porthopper/server.cpp
|
||||
services_daytime_client_SOURCES = \
|
||||
services/daytime_client.cpp \
|
||||
services/logger_service.cpp
|
||||
socks4_sync_client_SOURCES = socks4/sync_client.cpp
|
||||
timeouts_async_tcp_client_SOURCES = timeouts/async_tcp_client.cpp
|
||||
timeouts_blocking_tcp_client_SOURCES = timeouts/blocking_tcp_client.cpp
|
||||
timeouts_blocking_token_tcp_client_SOURCES = timeouts/blocking_token_tcp_client.cpp
|
||||
timeouts_blocking_udp_client_SOURCES = timeouts/blocking_udp_client.cpp
|
||||
timeouts_server_SOURCES = timeouts/server.cpp
|
||||
timers_time_t_timer_SOURCES = timers/time_t_timer.cpp
|
||||
tutorial_timer1_timer_SOURCES = tutorial/timer1/timer.cpp
|
||||
tutorial_timer2_timer_SOURCES = tutorial/timer2/timer.cpp
|
||||
tutorial_timer3_timer_SOURCES = tutorial/timer3/timer.cpp
|
||||
tutorial_timer4_timer_SOURCES = tutorial/timer4/timer.cpp
|
||||
tutorial_timer5_timer_SOURCES = tutorial/timer5/timer.cpp
|
||||
tutorial_daytime1_client_SOURCES = tutorial/daytime1/client.cpp
|
||||
tutorial_daytime2_server_SOURCES = tutorial/daytime2/server.cpp
|
||||
tutorial_daytime3_server_SOURCES = tutorial/daytime3/server.cpp
|
||||
tutorial_daytime4_client_SOURCES = tutorial/daytime4/client.cpp
|
||||
tutorial_daytime5_server_SOURCES = tutorial/daytime5/server.cpp
|
||||
tutorial_daytime6_server_SOURCES = tutorial/daytime6/server.cpp
|
||||
tutorial_daytime7_server_SOURCES = tutorial/daytime7/server.cpp
|
||||
|
||||
if !WINDOWS_TARGET
|
||||
chat_posix_chat_client_SOURCES = chat/posix_chat_client.cpp
|
||||
fork_daemon_SOURCES = fork/daemon.cpp
|
||||
fork_process_per_connection_SOURCES = fork/process_per_connection.cpp
|
||||
local_connect_pair_SOURCES = local/connect_pair.cpp
|
||||
local_iostream_client_SOURCES = local/iostream_client.cpp
|
||||
local_stream_server_SOURCES = local/stream_server.cpp
|
||||
local_stream_client_SOURCES = local/stream_client.cpp
|
||||
endif
|
||||
|
||||
if WINDOWS_TARGET
|
||||
windows_transmit_file_SOURCES = windows/transmit_file.cpp
|
||||
endif
|
||||
|
||||
if HAVE_OPENSSL
|
||||
ssl_client_SOURCES = ssl/client.cpp
|
||||
ssl_server_SOURCES = ssl/server.cpp
|
||||
endif
|
||||
|
||||
if HAVE_BOOST_COROUTINE
|
||||
spawn_echo_server_SOURCES = spawn/echo_server.cpp
|
||||
spawn_echo_server_LDADD = $(LDADD) -lboost_coroutine -lboost_context -lboost_thread -lboost_chrono -lboost_system
|
||||
spawn_parallel_grep_SOURCES = spawn/parallel_grep.cpp
|
||||
spawn_parallel_grep_LDADD = $(LDADD) -lboost_coroutine -lboost_context -lboost_thread -lboost_chrono -lboost_system
|
||||
endif
|
||||
|
||||
EXTRA_DIST = \
|
||||
http/server/connection.hpp \
|
||||
http/server/connection_manager.hpp \
|
||||
http/server/header.hpp \
|
||||
http/server/mime_types.hpp \
|
||||
http/server/reply.hpp \
|
||||
http/server/request.hpp \
|
||||
http/server/request_handler.hpp \
|
||||
http/server/request_parser.hpp \
|
||||
http/server/server.hpp \
|
||||
http/server2/connection.hpp \
|
||||
http/server2/io_context_pool.hpp \
|
||||
http/server2/header.hpp \
|
||||
http/server2/mime_types.hpp \
|
||||
http/server2/reply.hpp \
|
||||
http/server2/request.hpp \
|
||||
http/server2/request_handler.hpp \
|
||||
http/server2/request_parser.hpp \
|
||||
http/server2/server.hpp \
|
||||
http/server3/connection.hpp \
|
||||
http/server3/header.hpp \
|
||||
http/server3/mime_types.hpp \
|
||||
http/server3/reply.hpp \
|
||||
http/server3/request.hpp \
|
||||
http/server3/request_handler.hpp \
|
||||
http/server3/request_parser.hpp \
|
||||
http/server3/server.hpp \
|
||||
http/server4/file_handler.hpp \
|
||||
http/server4/header.hpp \
|
||||
http/server4/mime_types.hpp \
|
||||
http/server4/reply.hpp \
|
||||
http/server4/request.hpp \
|
||||
http/server4/request_parser.hpp \
|
||||
http/server4/server.hpp \
|
||||
icmp/icmp_header.hpp \
|
||||
icmp/ipv4_header.hpp \
|
||||
porthopper/protocol.hpp \
|
||||
serialization/client.cpp \
|
||||
serialization/server.cpp \
|
||||
serialization/connection.hpp \
|
||||
serialization/stock.hpp \
|
||||
services/basic_logger.hpp \
|
||||
services/logger.hpp \
|
||||
services/logger_service.hpp \
|
||||
socks4/socks4.hpp \
|
||||
ssl/README \
|
||||
ssl/ca.pem \
|
||||
ssl/server.pem \
|
||||
ssl/dh2048.pem
|
||||
|
||||
MAINTAINERCLEANFILES = \
|
||||
$(srcdir)/Makefile.in
|
||||
2339
asio/src/examples/cpp03/Makefile.in
Normal file
2339
asio/src/examples/cpp03/Makefile.in
Normal file
File diff suppressed because it is too large
Load Diff
285
asio/src/examples/cpp03/allocation/server.cpp
Normal file
285
asio/src/examples/cpp03/allocation/server.cpp
Normal file
@@ -0,0 +1,285 @@
|
||||
//
|
||||
// server.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <boost/aligned_storage.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
// Class to manage the memory to be used for handler-based custom allocation.
|
||||
// It contains a single block of memory which may be returned for allocation
|
||||
// requests. If the memory is in use when an allocation request is made, the
|
||||
// allocator delegates allocation to the global heap.
|
||||
class handler_memory
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
handler_memory()
|
||||
: in_use_(false)
|
||||
{
|
||||
}
|
||||
|
||||
void* allocate(std::size_t size)
|
||||
{
|
||||
if (!in_use_ && size < storage_.size)
|
||||
{
|
||||
in_use_ = true;
|
||||
return storage_.address();
|
||||
}
|
||||
else
|
||||
{
|
||||
return ::operator new(size);
|
||||
}
|
||||
}
|
||||
|
||||
void deallocate(void* pointer)
|
||||
{
|
||||
if (pointer == storage_.address())
|
||||
{
|
||||
in_use_ = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
::operator delete(pointer);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// Storage space used for handler-based custom memory allocation.
|
||||
boost::aligned_storage<1024> storage_;
|
||||
|
||||
// Whether the handler-based custom allocation storage has been used.
|
||||
bool in_use_;
|
||||
};
|
||||
|
||||
// The allocator to be associated with the handler objects. This allocator only
|
||||
// needs to satisfy the C++11 minimal allocator requirements, plus rebind when
|
||||
// targeting C++03.
|
||||
template <typename T>
|
||||
class handler_allocator
|
||||
{
|
||||
public:
|
||||
typedef T value_type;
|
||||
|
||||
explicit handler_allocator(handler_memory& mem)
|
||||
: memory_(mem)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
handler_allocator(const handler_allocator<U>& other)
|
||||
: memory_(other.memory_)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
struct rebind
|
||||
{
|
||||
typedef handler_allocator<U> other;
|
||||
};
|
||||
|
||||
bool operator==(const handler_allocator& other) const
|
||||
{
|
||||
return &memory_ == &other.memory_;
|
||||
}
|
||||
|
||||
bool operator!=(const handler_allocator& other) const
|
||||
{
|
||||
return &memory_ != &other.memory_;
|
||||
}
|
||||
|
||||
T* allocate(std::size_t n) const
|
||||
{
|
||||
return static_cast<T*>(memory_.allocate(sizeof(T) * n));
|
||||
}
|
||||
|
||||
void deallocate(T* p, std::size_t /*n*/) const
|
||||
{
|
||||
return memory_.deallocate(p);
|
||||
}
|
||||
|
||||
//private:
|
||||
// The underlying memory.
|
||||
handler_memory& memory_;
|
||||
};
|
||||
|
||||
// Wrapper class template for handler objects to allow handler memory
|
||||
// allocation to be customised. The allocator_type typedef and get_allocator()
|
||||
// member function are used by the asynchronous operations to obtain the
|
||||
// allocator. Calls to operator() are forwarded to the encapsulated handler.
|
||||
template <typename Handler>
|
||||
class custom_alloc_handler
|
||||
{
|
||||
public:
|
||||
typedef handler_allocator<Handler> allocator_type;
|
||||
|
||||
custom_alloc_handler(handler_memory& m, Handler h)
|
||||
: memory_(m),
|
||||
handler_(h)
|
||||
{
|
||||
}
|
||||
|
||||
allocator_type get_allocator() const
|
||||
{
|
||||
return allocator_type(memory_);
|
||||
}
|
||||
|
||||
template <typename Arg1>
|
||||
void operator()(Arg1 arg1)
|
||||
{
|
||||
handler_(arg1);
|
||||
}
|
||||
|
||||
template <typename Arg1, typename Arg2>
|
||||
void operator()(Arg1 arg1, Arg2 arg2)
|
||||
{
|
||||
handler_(arg1, arg2);
|
||||
}
|
||||
|
||||
private:
|
||||
handler_memory& memory_;
|
||||
Handler handler_;
|
||||
};
|
||||
|
||||
// Helper function to wrap a handler object to add custom allocation.
|
||||
template <typename Handler>
|
||||
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
|
||||
handler_memory& m, Handler h)
|
||||
{
|
||||
return custom_alloc_handler<Handler>(m, h);
|
||||
}
|
||||
|
||||
class session
|
||||
: public boost::enable_shared_from_this<session>
|
||||
{
|
||||
public:
|
||||
session(asio::io_context& io_context)
|
||||
: socket_(io_context)
|
||||
{
|
||||
}
|
||||
|
||||
tcp::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
make_custom_alloc_handler(handler_memory_,
|
||||
boost::bind(&session::handle_read,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred)));
|
||||
}
|
||||
|
||||
void handle_read(const asio::error_code& error,
|
||||
size_t bytes_transferred)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(data_, bytes_transferred),
|
||||
make_custom_alloc_handler(handler_memory_,
|
||||
boost::bind(&session::handle_write,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error)));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
make_custom_alloc_handler(handler_memory_,
|
||||
boost::bind(&session::handle_read,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred)));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// The socket used to communicate with the client.
|
||||
tcp::socket socket_;
|
||||
|
||||
// Buffer used to store data received from the client.
|
||||
boost::array<char, 1024> data_;
|
||||
|
||||
// The memory to use for handler-based custom memory allocation.
|
||||
handler_memory handler_memory_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<session> session_ptr;
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, short port)
|
||||
: io_context_(io_context),
|
||||
acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
|
||||
{
|
||||
session_ptr new_session(new session(io_context_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_accept(session_ptr new_session,
|
||||
const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
new_session->start();
|
||||
}
|
||||
|
||||
new_session.reset(new session(io_context_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
private:
|
||||
asio::io_context& io_context_;
|
||||
tcp::acceptor acceptor_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: server <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server s(io_context, atoi(argv[1]));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
131
asio/src/examples/cpp03/buffers/reference_counted.cpp
Normal file
131
asio/src/examples/cpp03/buffers/reference_counted.cpp
Normal file
@@ -0,0 +1,131 @@
|
||||
//
|
||||
// reference_counted.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
// A reference-counted non-modifiable buffer class.
|
||||
class shared_const_buffer
|
||||
{
|
||||
public:
|
||||
// Construct from a std::string.
|
||||
explicit shared_const_buffer(const std::string& data)
|
||||
: data_(new std::vector<char>(data.begin(), data.end())),
|
||||
buffer_(asio::buffer(*data_))
|
||||
{
|
||||
}
|
||||
|
||||
// Implement the ConstBufferSequence requirements.
|
||||
typedef asio::const_buffer value_type;
|
||||
typedef const asio::const_buffer* const_iterator;
|
||||
const asio::const_buffer* begin() const { return &buffer_; }
|
||||
const asio::const_buffer* end() const { return &buffer_ + 1; }
|
||||
|
||||
private:
|
||||
boost::shared_ptr<std::vector<char> > data_;
|
||||
asio::const_buffer buffer_;
|
||||
};
|
||||
|
||||
class session
|
||||
: public boost::enable_shared_from_this<session>
|
||||
{
|
||||
public:
|
||||
session(asio::io_context& io_context)
|
||||
: socket_(io_context)
|
||||
{
|
||||
}
|
||||
|
||||
tcp::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
using namespace std; // For time_t, time and ctime.
|
||||
time_t now = time(0);
|
||||
shared_const_buffer buffer(ctime(&now));
|
||||
asio::async_write(socket_, buffer,
|
||||
boost::bind(&session::handle_write, shared_from_this()));
|
||||
}
|
||||
|
||||
void handle_write()
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
// The socket used to communicate with the client.
|
||||
tcp::socket socket_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<session> session_ptr;
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, short port)
|
||||
: io_context_(io_context),
|
||||
acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
|
||||
{
|
||||
session_ptr new_session(new session(io_context_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_accept(session_ptr new_session,
|
||||
const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
new_session->start();
|
||||
}
|
||||
|
||||
new_session.reset(new session(io_context_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
private:
|
||||
asio::io_context& io_context_;
|
||||
tcp::acceptor acceptor_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: reference_counted <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server s(io_context, atoi(argv[1]));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
177
asio/src/examples/cpp03/chat/chat_client.cpp
Normal file
177
asio/src/examples/cpp03/chat/chat_client.cpp
Normal file
@@ -0,0 +1,177 @@
|
||||
//
|
||||
// chat_client.cpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "asio.hpp"
|
||||
#include "chat_message.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
typedef std::deque<chat_message> chat_message_queue;
|
||||
|
||||
class chat_client
|
||||
{
|
||||
public:
|
||||
chat_client(asio::io_context& io_context,
|
||||
const tcp::resolver::results_type& endpoints)
|
||||
: io_context_(io_context),
|
||||
socket_(io_context)
|
||||
{
|
||||
asio::async_connect(socket_, endpoints,
|
||||
boost::bind(&chat_client::handle_connect, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void write(const chat_message& msg)
|
||||
{
|
||||
asio::post(io_context_,
|
||||
boost::bind(&chat_client::do_write, this, msg));
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
asio::post(io_context_,
|
||||
boost::bind(&chat_client::do_close, this));
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void handle_connect(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
boost::bind(&chat_client::handle_read_header, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_header(const asio::error_code& error)
|
||||
{
|
||||
if (!error && read_msg_.decode_header())
|
||||
{
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.body(), read_msg_.body_length()),
|
||||
boost::bind(&chat_client::handle_read_body, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
do_close();
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_body(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
std::cout.write(read_msg_.body(), read_msg_.body_length());
|
||||
std::cout << "\n";
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
boost::bind(&chat_client::handle_read_header, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
do_close();
|
||||
}
|
||||
}
|
||||
|
||||
void do_write(chat_message msg)
|
||||
{
|
||||
bool write_in_progress = !write_msgs_.empty();
|
||||
write_msgs_.push_back(msg);
|
||||
if (!write_in_progress)
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msgs_.front().data(),
|
||||
write_msgs_.front().length()),
|
||||
boost::bind(&chat_client::handle_write, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
write_msgs_.pop_front();
|
||||
if (!write_msgs_.empty())
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msgs_.front().data(),
|
||||
write_msgs_.front().length()),
|
||||
boost::bind(&chat_client::handle_write, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
do_close();
|
||||
}
|
||||
}
|
||||
|
||||
void do_close()
|
||||
{
|
||||
socket_.close();
|
||||
}
|
||||
|
||||
private:
|
||||
asio::io_context& io_context_;
|
||||
tcp::socket socket_;
|
||||
chat_message read_msg_;
|
||||
chat_message_queue write_msgs_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cerr << "Usage: chat_client <host> <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
tcp::resolver resolver(io_context);
|
||||
tcp::resolver::results_type endpoints = resolver.resolve(argv[1], argv[2]);
|
||||
|
||||
chat_client c(io_context, endpoints);
|
||||
|
||||
asio::thread t(boost::bind(&asio::io_context::run, &io_context));
|
||||
|
||||
char line[chat_message::max_body_length + 1];
|
||||
while (std::cin.getline(line, chat_message::max_body_length + 1))
|
||||
{
|
||||
using namespace std; // For strlen and memcpy.
|
||||
chat_message msg;
|
||||
msg.body_length(strlen(line));
|
||||
memcpy(msg.body(), line, msg.body_length());
|
||||
msg.encode_header();
|
||||
c.write(msg);
|
||||
}
|
||||
|
||||
c.close();
|
||||
t.join();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
93
asio/src/examples/cpp03/chat/chat_message.hpp
Normal file
93
asio/src/examples/cpp03/chat/chat_message.hpp
Normal file
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// chat_message.hpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef CHAT_MESSAGE_HPP
|
||||
#define CHAT_MESSAGE_HPP
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
class chat_message
|
||||
{
|
||||
public:
|
||||
enum { header_length = 4 };
|
||||
enum { max_body_length = 512 };
|
||||
|
||||
chat_message()
|
||||
: body_length_(0)
|
||||
{
|
||||
}
|
||||
|
||||
const char* data() const
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
char* data()
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
size_t length() const
|
||||
{
|
||||
return header_length + body_length_;
|
||||
}
|
||||
|
||||
const char* body() const
|
||||
{
|
||||
return data_ + header_length;
|
||||
}
|
||||
|
||||
char* body()
|
||||
{
|
||||
return data_ + header_length;
|
||||
}
|
||||
|
||||
size_t body_length() const
|
||||
{
|
||||
return body_length_;
|
||||
}
|
||||
|
||||
void body_length(size_t new_length)
|
||||
{
|
||||
body_length_ = new_length;
|
||||
if (body_length_ > max_body_length)
|
||||
body_length_ = max_body_length;
|
||||
}
|
||||
|
||||
bool decode_header()
|
||||
{
|
||||
using namespace std; // For strncat and atoi.
|
||||
char header[header_length + 1] = "";
|
||||
strncat(header, data_, header_length);
|
||||
body_length_ = atoi(header);
|
||||
if (body_length_ > max_body_length)
|
||||
{
|
||||
body_length_ = 0;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void encode_header()
|
||||
{
|
||||
using namespace std; // For sprintf and memcpy.
|
||||
char header[header_length + 1] = "";
|
||||
sprintf(header, "%4d", static_cast<int>(body_length_));
|
||||
memcpy(data_, header, header_length);
|
||||
}
|
||||
|
||||
private:
|
||||
char data_[header_length + max_body_length];
|
||||
size_t body_length_;
|
||||
};
|
||||
|
||||
#endif // CHAT_MESSAGE_HPP
|
||||
249
asio/src/examples/cpp03/chat/chat_server.cpp
Normal file
249
asio/src/examples/cpp03/chat/chat_server.cpp
Normal file
@@ -0,0 +1,249 @@
|
||||
//
|
||||
// chat_server.cpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <set>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include "asio.hpp"
|
||||
#include "chat_message.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
typedef std::deque<chat_message> chat_message_queue;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_participant
|
||||
{
|
||||
public:
|
||||
virtual ~chat_participant() {}
|
||||
virtual void deliver(const chat_message& msg) = 0;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<chat_participant> chat_participant_ptr;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_room
|
||||
{
|
||||
public:
|
||||
void join(chat_participant_ptr participant)
|
||||
{
|
||||
participants_.insert(participant);
|
||||
std::for_each(recent_msgs_.begin(), recent_msgs_.end(),
|
||||
boost::bind(&chat_participant::deliver,
|
||||
participant, boost::placeholders::_1));
|
||||
}
|
||||
|
||||
void leave(chat_participant_ptr participant)
|
||||
{
|
||||
participants_.erase(participant);
|
||||
}
|
||||
|
||||
void deliver(const chat_message& msg)
|
||||
{
|
||||
recent_msgs_.push_back(msg);
|
||||
while (recent_msgs_.size() > max_recent_msgs)
|
||||
recent_msgs_.pop_front();
|
||||
|
||||
std::for_each(participants_.begin(), participants_.end(),
|
||||
boost::bind(&chat_participant::deliver,
|
||||
boost::placeholders::_1, boost::ref(msg)));
|
||||
}
|
||||
|
||||
private:
|
||||
std::set<chat_participant_ptr> participants_;
|
||||
enum { max_recent_msgs = 100 };
|
||||
chat_message_queue recent_msgs_;
|
||||
};
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_session
|
||||
: public chat_participant,
|
||||
public boost::enable_shared_from_this<chat_session>
|
||||
{
|
||||
public:
|
||||
chat_session(asio::io_context& io_context, chat_room& room)
|
||||
: socket_(io_context),
|
||||
room_(room)
|
||||
{
|
||||
}
|
||||
|
||||
tcp::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
room_.join(shared_from_this());
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
boost::bind(
|
||||
&chat_session::handle_read_header, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void deliver(const chat_message& msg)
|
||||
{
|
||||
bool write_in_progress = !write_msgs_.empty();
|
||||
write_msgs_.push_back(msg);
|
||||
if (!write_in_progress)
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msgs_.front().data(),
|
||||
write_msgs_.front().length()),
|
||||
boost::bind(&chat_session::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_header(const asio::error_code& error)
|
||||
{
|
||||
if (!error && read_msg_.decode_header())
|
||||
{
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.body(), read_msg_.body_length()),
|
||||
boost::bind(&chat_session::handle_read_body, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
room_.leave(shared_from_this());
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_body(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
room_.deliver(read_msg_);
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
boost::bind(&chat_session::handle_read_header, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
room_.leave(shared_from_this());
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
write_msgs_.pop_front();
|
||||
if (!write_msgs_.empty())
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msgs_.front().data(),
|
||||
write_msgs_.front().length()),
|
||||
boost::bind(&chat_session::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
room_.leave(shared_from_this());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
tcp::socket socket_;
|
||||
chat_room& room_;
|
||||
chat_message read_msg_;
|
||||
chat_message_queue write_msgs_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<chat_session> chat_session_ptr;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_server
|
||||
{
|
||||
public:
|
||||
chat_server(asio::io_context& io_context,
|
||||
const tcp::endpoint& endpoint)
|
||||
: io_context_(io_context),
|
||||
acceptor_(io_context, endpoint)
|
||||
{
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void start_accept()
|
||||
{
|
||||
chat_session_ptr new_session(new chat_session(io_context_, room_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&chat_server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_accept(chat_session_ptr session,
|
||||
const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
session->start();
|
||||
}
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
private:
|
||||
asio::io_context& io_context_;
|
||||
tcp::acceptor acceptor_;
|
||||
chat_room room_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<chat_server> chat_server_ptr;
|
||||
typedef std::list<chat_server_ptr> chat_server_list;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc < 2)
|
||||
{
|
||||
std::cerr << "Usage: chat_server <port> [<port> ...]\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
chat_server_list servers;
|
||||
for (int i = 1; i < argc; ++i)
|
||||
{
|
||||
using namespace std; // For atoi.
|
||||
tcp::endpoint endpoint(tcp::v4(), atoi(argv[i]));
|
||||
chat_server_ptr server(new chat_server(io_context, endpoint));
|
||||
servers.push_back(server);
|
||||
}
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
204
asio/src/examples/cpp03/chat/posix_chat_client.cpp
Normal file
204
asio/src/examples/cpp03/chat/posix_chat_client.cpp
Normal file
@@ -0,0 +1,204 @@
|
||||
//
|
||||
// posix_chat_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "asio.hpp"
|
||||
#include "chat_message.hpp"
|
||||
|
||||
#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
||||
|
||||
using asio::ip::tcp;
|
||||
namespace posix = asio::posix;
|
||||
|
||||
class posix_chat_client
|
||||
{
|
||||
public:
|
||||
posix_chat_client(asio::io_context& io_context,
|
||||
const tcp::resolver::results_type& endpoints)
|
||||
: socket_(io_context),
|
||||
input_(io_context, ::dup(STDIN_FILENO)),
|
||||
output_(io_context, ::dup(STDOUT_FILENO)),
|
||||
input_buffer_(chat_message::max_body_length)
|
||||
{
|
||||
asio::async_connect(socket_, endpoints,
|
||||
boost::bind(&posix_chat_client::handle_connect, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void handle_connect(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
// Read the fixed-length header of the next message from the server.
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
boost::bind(&posix_chat_client::handle_read_header, this,
|
||||
asio::placeholders::error));
|
||||
|
||||
// Read a line of input entered by the user.
|
||||
asio::async_read_until(input_, input_buffer_, '\n',
|
||||
boost::bind(&posix_chat_client::handle_read_input, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_header(const asio::error_code& error)
|
||||
{
|
||||
if (!error && read_msg_.decode_header())
|
||||
{
|
||||
// Read the variable-length body of the message from the server.
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.body(), read_msg_.body_length()),
|
||||
boost::bind(&posix_chat_client::handle_read_body, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_body(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
// Write out the message we just received, terminated by a newline.
|
||||
static char eol[] = { '\n' };
|
||||
boost::array<asio::const_buffer, 2> buffers = {{
|
||||
asio::buffer(read_msg_.body(), read_msg_.body_length()),
|
||||
asio::buffer(eol) }};
|
||||
asio::async_write(output_, buffers,
|
||||
boost::bind(&posix_chat_client::handle_write_output, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write_output(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
// Read the fixed-length header of the next message from the server.
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
boost::bind(&posix_chat_client::handle_read_header, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_input(const asio::error_code& error,
|
||||
std::size_t length)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
// Write the message (minus the newline) to the server.
|
||||
write_msg_.body_length(length - 1);
|
||||
input_buffer_.sgetn(write_msg_.body(), length - 1);
|
||||
input_buffer_.consume(1); // Remove newline from input.
|
||||
write_msg_.encode_header();
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msg_.data(), write_msg_.length()),
|
||||
boost::bind(&posix_chat_client::handle_write, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else if (error == asio::error::not_found)
|
||||
{
|
||||
// Didn't get a newline. Send whatever we have.
|
||||
write_msg_.body_length(input_buffer_.size());
|
||||
input_buffer_.sgetn(write_msg_.body(), input_buffer_.size());
|
||||
write_msg_.encode_header();
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msg_.data(), write_msg_.length()),
|
||||
boost::bind(&posix_chat_client::handle_write, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
// Read a line of input entered by the user.
|
||||
asio::async_read_until(input_, input_buffer_, '\n',
|
||||
boost::bind(&posix_chat_client::handle_read_input, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
else
|
||||
{
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
// Cancel all outstanding asynchronous operations.
|
||||
socket_.close();
|
||||
input_.close();
|
||||
output_.close();
|
||||
}
|
||||
|
||||
private:
|
||||
tcp::socket socket_;
|
||||
posix::stream_descriptor input_;
|
||||
posix::stream_descriptor output_;
|
||||
chat_message read_msg_;
|
||||
chat_message write_msg_;
|
||||
asio::streambuf input_buffer_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cerr << "Usage: posix_chat_client <host> <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
tcp::resolver resolver(io_context);
|
||||
tcp::resolver::results_type endpoints = resolver.resolve(argv[1], argv[2]);
|
||||
|
||||
posix_chat_client c(io_context, endpoints);
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
||||
int main() {}
|
||||
#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
|
||||
137
asio/src/examples/cpp03/echo/async_tcp_echo_server.cpp
Normal file
137
asio/src/examples/cpp03/echo/async_tcp_echo_server.cpp
Normal file
@@ -0,0 +1,137 @@
|
||||
//
|
||||
// async_tcp_echo_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
class session
|
||||
{
|
||||
public:
|
||||
session(asio::io_context& io_context)
|
||||
: socket_(io_context)
|
||||
{
|
||||
}
|
||||
|
||||
tcp::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_, max_length),
|
||||
boost::bind(&session::handle_read, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
private:
|
||||
void handle_read(const asio::error_code& error,
|
||||
size_t bytes_transferred)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(data_, bytes_transferred),
|
||||
boost::bind(&session::handle_write, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
delete this;
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_, max_length),
|
||||
boost::bind(&session::handle_read, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
else
|
||||
{
|
||||
delete this;
|
||||
}
|
||||
}
|
||||
|
||||
tcp::socket socket_;
|
||||
enum { max_length = 1024 };
|
||||
char data_[max_length];
|
||||
};
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, short port)
|
||||
: io_context_(io_context),
|
||||
acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
|
||||
{
|
||||
start_accept();
|
||||
}
|
||||
|
||||
private:
|
||||
void start_accept()
|
||||
{
|
||||
session* new_session = new session(io_context_);
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_accept(session* new_session,
|
||||
const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
new_session->start();
|
||||
}
|
||||
else
|
||||
{
|
||||
delete new_session;
|
||||
}
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
asio::io_context& io_context_;
|
||||
tcp::acceptor acceptor_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: async_tcp_echo_server <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server s(io_context, atoi(argv[1]));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
92
asio/src/examples/cpp03/echo/async_udp_echo_server.cpp
Normal file
92
asio/src/examples/cpp03/echo/async_udp_echo_server.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
//
|
||||
// async_udp_echo_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::udp;
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, short port)
|
||||
: socket_(io_context, udp::endpoint(udp::v4(), port))
|
||||
{
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(data_, max_length), sender_endpoint_,
|
||||
boost::bind(&server::handle_receive_from, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void handle_receive_from(const asio::error_code& error,
|
||||
size_t bytes_recvd)
|
||||
{
|
||||
if (!error && bytes_recvd > 0)
|
||||
{
|
||||
socket_.async_send_to(
|
||||
asio::buffer(data_, bytes_recvd), sender_endpoint_,
|
||||
boost::bind(&server::handle_send_to, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(data_, max_length), sender_endpoint_,
|
||||
boost::bind(&server::handle_receive_from, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_send_to(const asio::error_code& /*error*/,
|
||||
size_t /*bytes_sent*/)
|
||||
{
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(data_, max_length), sender_endpoint_,
|
||||
boost::bind(&server::handle_receive_from, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
private:
|
||||
udp::socket socket_;
|
||||
udp::endpoint sender_endpoint_;
|
||||
enum { max_length = 1024 };
|
||||
char data_[max_length];
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: async_udp_echo_server <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server s(io_context, atoi(argv[1]));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
59
asio/src/examples/cpp03/echo/blocking_tcp_echo_client.cpp
Normal file
59
asio/src/examples/cpp03/echo/blocking_tcp_echo_client.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
//
|
||||
// blocking_tcp_echo_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
enum { max_length = 1024 };
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
tcp::resolver resolver(io_context);
|
||||
tcp::resolver::results_type endpoints =
|
||||
resolver.resolve(tcp::v4(), argv[1], argv[2]);
|
||||
|
||||
tcp::socket s(io_context);
|
||||
asio::connect(s, endpoints);
|
||||
|
||||
using namespace std; // For strlen.
|
||||
std::cout << "Enter message: ";
|
||||
char request[max_length];
|
||||
std::cin.getline(request, max_length);
|
||||
size_t request_length = strlen(request);
|
||||
asio::write(s, asio::buffer(request, request_length));
|
||||
|
||||
char reply[max_length];
|
||||
size_t reply_length = asio::read(s,
|
||||
asio::buffer(reply, request_length));
|
||||
std::cout << "Reply is: ";
|
||||
std::cout.write(reply, reply_length);
|
||||
std::cout << "\n";
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
79
asio/src/examples/cpp03/echo/blocking_tcp_echo_server.cpp
Normal file
79
asio/src/examples/cpp03/echo/blocking_tcp_echo_server.cpp
Normal file
@@ -0,0 +1,79 @@
|
||||
//
|
||||
// blocking_tcp_echo_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/smart_ptr.hpp>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
const int max_length = 1024;
|
||||
|
||||
typedef boost::shared_ptr<tcp::socket> socket_ptr;
|
||||
|
||||
void session(socket_ptr sock)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
char data[max_length];
|
||||
|
||||
asio::error_code error;
|
||||
size_t length = sock->read_some(asio::buffer(data), error);
|
||||
if (error == asio::error::eof)
|
||||
break; // Connection closed cleanly by peer.
|
||||
else if (error)
|
||||
throw asio::system_error(error); // Some other error.
|
||||
|
||||
asio::write(*sock, asio::buffer(data, length));
|
||||
}
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception in thread: " << e.what() << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void server(asio::io_context& io_context, unsigned short port)
|
||||
{
|
||||
tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
|
||||
for (;;)
|
||||
{
|
||||
socket_ptr sock(new tcp::socket(io_context));
|
||||
a.accept(*sock);
|
||||
asio::thread t(boost::bind(session, sock));
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server(io_context, atoi(argv[1]));
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
59
asio/src/examples/cpp03/echo/blocking_udp_echo_client.cpp
Normal file
59
asio/src/examples/cpp03/echo/blocking_udp_echo_client.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
//
|
||||
// blocking_udp_echo_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::udp;
|
||||
|
||||
enum { max_length = 1024 };
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
udp::socket s(io_context, udp::endpoint(udp::v4(), 0));
|
||||
|
||||
udp::resolver resolver(io_context);
|
||||
udp::resolver::results_type endpoints =
|
||||
resolver.resolve(udp::v4(), argv[1], argv[2]);
|
||||
|
||||
using namespace std; // For strlen.
|
||||
std::cout << "Enter message: ";
|
||||
char request[max_length];
|
||||
std::cin.getline(request, max_length);
|
||||
size_t request_length = strlen(request);
|
||||
s.send_to(asio::buffer(request, request_length), *endpoints.begin());
|
||||
|
||||
char reply[max_length];
|
||||
udp::endpoint sender_endpoint;
|
||||
size_t reply_length = s.receive_from(
|
||||
asio::buffer(reply, max_length), sender_endpoint);
|
||||
std::cout << "Reply is: ";
|
||||
std::cout.write(reply, reply_length);
|
||||
std::cout << "\n";
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
53
asio/src/examples/cpp03/echo/blocking_udp_echo_server.cpp
Normal file
53
asio/src/examples/cpp03/echo/blocking_udp_echo_server.cpp
Normal file
@@ -0,0 +1,53 @@
|
||||
//
|
||||
// blocking_udp_echo_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::udp;
|
||||
|
||||
enum { max_length = 1024 };
|
||||
|
||||
void server(asio::io_context& io_context, unsigned short port)
|
||||
{
|
||||
udp::socket sock(io_context, udp::endpoint(udp::v4(), port));
|
||||
for (;;)
|
||||
{
|
||||
char data[max_length];
|
||||
udp::endpoint sender_endpoint;
|
||||
size_t length = sock.receive_from(
|
||||
asio::buffer(data, max_length), sender_endpoint);
|
||||
sock.send_to(asio::buffer(data, length), sender_endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: blocking_udp_echo_server <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server(io_context, atoi(argv[1]));
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
190
asio/src/examples/cpp03/fork/daemon.cpp
Normal file
190
asio/src/examples/cpp03/fork/daemon.cpp
Normal file
@@ -0,0 +1,190 @@
|
||||
//
|
||||
// daemon.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <asio/io_context.hpp>
|
||||
#include <asio/ip/udp.hpp>
|
||||
#include <asio/signal_set.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
#include <syslog.h>
|
||||
#include <unistd.h>
|
||||
|
||||
using asio::ip::udp;
|
||||
|
||||
class udp_daytime_server
|
||||
{
|
||||
public:
|
||||
udp_daytime_server(asio::io_context& io_context)
|
||||
: socket_(io_context, udp::endpoint(udp::v4(), 13))
|
||||
{
|
||||
start_receive();
|
||||
}
|
||||
|
||||
private:
|
||||
void start_receive()
|
||||
{
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(recv_buffer_), remote_endpoint_,
|
||||
boost::bind(&udp_daytime_server::handle_receive,
|
||||
this, boost::placeholders::_1));
|
||||
}
|
||||
|
||||
void handle_receive(const asio::error_code& ec)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
using namespace std; // For time_t, time and ctime;
|
||||
time_t now = time(0);
|
||||
std::string message = ctime(&now);
|
||||
|
||||
asio::error_code ignored_ec;
|
||||
socket_.send_to(asio::buffer(message),
|
||||
remote_endpoint_, 0, ignored_ec);
|
||||
}
|
||||
|
||||
start_receive();
|
||||
}
|
||||
|
||||
udp::socket socket_;
|
||||
udp::endpoint remote_endpoint_;
|
||||
boost::array<char, 1> recv_buffer_;
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
asio::io_context io_context;
|
||||
|
||||
// Initialise the server before becoming a daemon. If the process is
|
||||
// started from a shell, this means any errors will be reported back to the
|
||||
// user.
|
||||
udp_daytime_server server(io_context);
|
||||
|
||||
// Register signal handlers so that the daemon may be shut down. You may
|
||||
// also want to register for other signals, such as SIGHUP to trigger a
|
||||
// re-read of a configuration file.
|
||||
asio::signal_set signals(io_context, SIGINT, SIGTERM);
|
||||
signals.async_wait(
|
||||
boost::bind(&asio::io_context::stop, &io_context));
|
||||
|
||||
// Inform the io_context that we are about to become a daemon. The
|
||||
// io_context cleans up any internal resources, such as threads, that may
|
||||
// interfere with forking.
|
||||
io_context.notify_fork(asio::io_context::fork_prepare);
|
||||
|
||||
// Fork the process and have the parent exit. If the process was started
|
||||
// from a shell, this returns control to the user. Forking a new process is
|
||||
// also a prerequisite for the subsequent call to setsid().
|
||||
if (pid_t pid = fork())
|
||||
{
|
||||
if (pid > 0)
|
||||
{
|
||||
// We're in the parent process and need to exit.
|
||||
//
|
||||
// When the exit() function is used, the program terminates without
|
||||
// invoking local variables' destructors. Only global variables are
|
||||
// destroyed. As the io_context object is a local variable, this means
|
||||
// we do not have to call:
|
||||
//
|
||||
// io_context.notify_fork(asio::io_context::fork_parent);
|
||||
//
|
||||
// However, this line should be added before each call to exit() if
|
||||
// using a global io_context object. An additional call:
|
||||
//
|
||||
// io_context.notify_fork(asio::io_context::fork_prepare);
|
||||
//
|
||||
// should also precede the second fork().
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
syslog(LOG_ERR | LOG_USER, "First fork failed: %m");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Make the process a new session leader. This detaches it from the
|
||||
// terminal.
|
||||
setsid();
|
||||
|
||||
// A process inherits its working directory from its parent. This could be
|
||||
// on a mounted filesystem, which means that the running daemon would
|
||||
// prevent this filesystem from being unmounted. Changing to the root
|
||||
// directory avoids this problem.
|
||||
chdir("/");
|
||||
|
||||
// The file mode creation mask is also inherited from the parent process.
|
||||
// We don't want to restrict the permissions on files created by the
|
||||
// daemon, so the mask is cleared.
|
||||
umask(0);
|
||||
|
||||
// A second fork ensures the process cannot acquire a controlling terminal.
|
||||
if (pid_t pid = fork())
|
||||
{
|
||||
if (pid > 0)
|
||||
{
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
syslog(LOG_ERR | LOG_USER, "Second fork failed: %m");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Close the standard streams. This decouples the daemon from the terminal
|
||||
// that started it.
|
||||
close(0);
|
||||
close(1);
|
||||
close(2);
|
||||
|
||||
// We don't want the daemon to have any standard input.
|
||||
if (open("/dev/null", O_RDONLY) < 0)
|
||||
{
|
||||
syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Send standard output to a log file.
|
||||
const char* output = "/tmp/asio.daemon.out";
|
||||
const int flags = O_WRONLY | O_CREAT | O_APPEND;
|
||||
const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
|
||||
if (open(output, flags, mode) < 0)
|
||||
{
|
||||
syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Also send standard error to the same log file.
|
||||
if (dup(1) < 0)
|
||||
{
|
||||
syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Inform the io_context that we have finished becoming a daemon. The
|
||||
// io_context uses this opportunity to create any internal file descriptors
|
||||
// that need to be private to the new process.
|
||||
io_context.notify_fork(asio::io_context::fork_child);
|
||||
|
||||
// The io_context can now be used normally.
|
||||
syslog(LOG_INFO | LOG_USER, "Daemon started");
|
||||
io_context.run();
|
||||
syslog(LOG_INFO | LOG_USER, "Daemon stopped");
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what());
|
||||
std::cerr << "Exception: " << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
161
asio/src/examples/cpp03/fork/process_per_connection.cpp
Normal file
161
asio/src/examples/cpp03/fork/process_per_connection.cpp
Normal file
@@ -0,0 +1,161 @@
|
||||
//
|
||||
// process_per_connection.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <asio/io_context.hpp>
|
||||
#include <asio/ip/tcp.hpp>
|
||||
#include <asio/signal_set.hpp>
|
||||
#include <asio/write.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, unsigned short port)
|
||||
: io_context_(io_context),
|
||||
signal_(io_context, SIGCHLD),
|
||||
acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
|
||||
socket_(io_context)
|
||||
{
|
||||
start_signal_wait();
|
||||
start_accept();
|
||||
}
|
||||
|
||||
private:
|
||||
void start_signal_wait()
|
||||
{
|
||||
signal_.async_wait(boost::bind(&server::handle_signal_wait, this));
|
||||
}
|
||||
|
||||
void handle_signal_wait()
|
||||
{
|
||||
// Only the parent process should check for this signal. We can determine
|
||||
// whether we are in the parent by checking if the acceptor is still open.
|
||||
if (acceptor_.is_open())
|
||||
{
|
||||
// Reap completed child processes so that we don't end up with zombies.
|
||||
int status = 0;
|
||||
while (waitpid(-1, &status, WNOHANG) > 0) {}
|
||||
|
||||
start_signal_wait();
|
||||
}
|
||||
}
|
||||
|
||||
void start_accept()
|
||||
{
|
||||
acceptor_.async_accept(socket_,
|
||||
boost::bind(&server::handle_accept, this, boost::placeholders::_1));
|
||||
}
|
||||
|
||||
void handle_accept(const asio::error_code& ec)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
// Inform the io_context that we are about to fork. The io_context cleans
|
||||
// up any internal resources, such as threads, that may interfere with
|
||||
// forking.
|
||||
io_context_.notify_fork(asio::io_context::fork_prepare);
|
||||
|
||||
if (fork() == 0)
|
||||
{
|
||||
// Inform the io_context that the fork is finished and that this is the
|
||||
// child process. The io_context uses this opportunity to create any
|
||||
// internal file descriptors that must be private to the new process.
|
||||
io_context_.notify_fork(asio::io_context::fork_child);
|
||||
|
||||
// The child won't be accepting new connections, so we can close the
|
||||
// acceptor. It remains open in the parent.
|
||||
acceptor_.close();
|
||||
|
||||
// The child process is not interested in processing the SIGCHLD signal.
|
||||
signal_.cancel();
|
||||
|
||||
start_read();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Inform the io_context that the fork is finished (or failed) and that
|
||||
// this is the parent process. The io_context uses this opportunity to
|
||||
// recreate any internal resources that were cleaned up during
|
||||
// preparation for the fork.
|
||||
io_context_.notify_fork(asio::io_context::fork_parent);
|
||||
|
||||
socket_.close();
|
||||
start_accept();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cerr << "Accept error: " << ec.message() << std::endl;
|
||||
start_accept();
|
||||
}
|
||||
}
|
||||
|
||||
void start_read()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
boost::bind(&server::handle_read, this,
|
||||
boost::placeholders::_1, boost::placeholders::_2));
|
||||
}
|
||||
|
||||
void handle_read(const asio::error_code& ec, std::size_t length)
|
||||
{
|
||||
if (!ec)
|
||||
start_write(length);
|
||||
}
|
||||
|
||||
void start_write(std::size_t length)
|
||||
{
|
||||
asio::async_write(socket_, asio::buffer(data_, length),
|
||||
boost::bind(&server::handle_write, this, boost::placeholders::_1));
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& ec)
|
||||
{
|
||||
if (!ec)
|
||||
start_read();
|
||||
}
|
||||
|
||||
asio::io_context& io_context_;
|
||||
asio::signal_set signal_;
|
||||
tcp::acceptor acceptor_;
|
||||
tcp::socket socket_;
|
||||
boost::array<char, 1024> data_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: process_per_connection <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server s(io_context, atoi(argv[1]));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
204
asio/src/examples/cpp03/http/client/async_client.cpp
Normal file
204
asio/src/examples/cpp03/http/client/async_client.cpp
Normal file
@@ -0,0 +1,204 @@
|
||||
//
|
||||
// async_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
class client
|
||||
{
|
||||
public:
|
||||
client(asio::io_context& io_context,
|
||||
const std::string& server, const std::string& path)
|
||||
: resolver_(io_context),
|
||||
socket_(io_context)
|
||||
{
|
||||
// Form the request. We specify the "Connection: close" header so that the
|
||||
// server will close the socket after transmitting the response. This will
|
||||
// allow us to treat all data up until the EOF as the content.
|
||||
std::ostream request_stream(&request_);
|
||||
request_stream << "GET " << path << " HTTP/1.0\r\n";
|
||||
request_stream << "Host: " << server << "\r\n";
|
||||
request_stream << "Accept: */*\r\n";
|
||||
request_stream << "Connection: close\r\n\r\n";
|
||||
|
||||
// Start an asynchronous resolve to translate the server and service names
|
||||
// into a list of endpoints.
|
||||
resolver_.async_resolve(server, "http",
|
||||
boost::bind(&client::handle_resolve, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::results));
|
||||
}
|
||||
|
||||
private:
|
||||
void handle_resolve(const asio::error_code& err,
|
||||
const tcp::resolver::results_type& endpoints)
|
||||
{
|
||||
if (!err)
|
||||
{
|
||||
// Attempt a connection to each endpoint in the list until we
|
||||
// successfully establish a connection.
|
||||
asio::async_connect(socket_, endpoints,
|
||||
boost::bind(&client::handle_connect, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Error: " << err.message() << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void handle_connect(const asio::error_code& err)
|
||||
{
|
||||
if (!err)
|
||||
{
|
||||
// The connection was successful. Send the request.
|
||||
asio::async_write(socket_, request_,
|
||||
boost::bind(&client::handle_write_request, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Error: " << err.message() << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write_request(const asio::error_code& err)
|
||||
{
|
||||
if (!err)
|
||||
{
|
||||
// Read the response status line. The response_ streambuf will
|
||||
// automatically grow to accommodate the entire line. The growth may be
|
||||
// limited by passing a maximum size to the streambuf constructor.
|
||||
asio::async_read_until(socket_, response_, "\r\n",
|
||||
boost::bind(&client::handle_read_status_line, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Error: " << err.message() << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_status_line(const asio::error_code& err)
|
||||
{
|
||||
if (!err)
|
||||
{
|
||||
// Check that response is OK.
|
||||
std::istream response_stream(&response_);
|
||||
std::string http_version;
|
||||
response_stream >> http_version;
|
||||
unsigned int status_code;
|
||||
response_stream >> status_code;
|
||||
std::string status_message;
|
||||
std::getline(response_stream, status_message);
|
||||
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
|
||||
{
|
||||
std::cout << "Invalid response\n";
|
||||
return;
|
||||
}
|
||||
if (status_code != 200)
|
||||
{
|
||||
std::cout << "Response returned with status code ";
|
||||
std::cout << status_code << "\n";
|
||||
return;
|
||||
}
|
||||
|
||||
// Read the response headers, which are terminated by a blank line.
|
||||
asio::async_read_until(socket_, response_, "\r\n\r\n",
|
||||
boost::bind(&client::handle_read_headers, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Error: " << err << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_headers(const asio::error_code& err)
|
||||
{
|
||||
if (!err)
|
||||
{
|
||||
// Process the response headers.
|
||||
std::istream response_stream(&response_);
|
||||
std::string header;
|
||||
while (std::getline(response_stream, header) && header != "\r")
|
||||
std::cout << header << "\n";
|
||||
std::cout << "\n";
|
||||
|
||||
// Write whatever content we already have to output.
|
||||
if (response_.size() > 0)
|
||||
std::cout << &response_;
|
||||
|
||||
// Start reading remaining data until EOF.
|
||||
asio::async_read(socket_, response_,
|
||||
asio::transfer_at_least(1),
|
||||
boost::bind(&client::handle_read_content, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Error: " << err << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read_content(const asio::error_code& err)
|
||||
{
|
||||
if (!err)
|
||||
{
|
||||
// Write all of the data that has been read so far.
|
||||
std::cout << &response_;
|
||||
|
||||
// Continue reading remaining data until EOF.
|
||||
asio::async_read(socket_, response_,
|
||||
asio::transfer_at_least(1),
|
||||
boost::bind(&client::handle_read_content, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else if (err != asio::error::eof)
|
||||
{
|
||||
std::cout << "Error: " << err << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
tcp::resolver resolver_;
|
||||
tcp::socket socket_;
|
||||
asio::streambuf request_;
|
||||
asio::streambuf response_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cout << "Usage: async_client <server> <path>\n";
|
||||
std::cout << "Example:\n";
|
||||
std::cout << " async_client www.boost.org /LICENSE_1_0.txt\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
client c(io_context, argv[1], argv[2]);
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cout << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
106
asio/src/examples/cpp03/http/client/sync_client.cpp
Normal file
106
asio/src/examples/cpp03/http/client/sync_client.cpp
Normal file
@@ -0,0 +1,106 @@
|
||||
//
|
||||
// sync_client.cpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cout << "Usage: sync_client <server> <path>\n";
|
||||
std::cout << "Example:\n";
|
||||
std::cout << " sync_client www.boost.org /LICENSE_1_0.txt\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
// Get a list of endpoints corresponding to the server name.
|
||||
tcp::resolver resolver(io_context);
|
||||
tcp::resolver::results_type endpoints = resolver.resolve(argv[1], "http");
|
||||
|
||||
// Try each endpoint until we successfully establish a connection.
|
||||
tcp::socket socket(io_context);
|
||||
asio::connect(socket, endpoints);
|
||||
|
||||
// Form the request. We specify the "Connection: close" header so that the
|
||||
// server will close the socket after transmitting the response. This will
|
||||
// allow us to treat all data up until the EOF as the content.
|
||||
asio::streambuf request;
|
||||
std::ostream request_stream(&request);
|
||||
request_stream << "GET " << argv[2] << " HTTP/1.0\r\n";
|
||||
request_stream << "Host: " << argv[1] << "\r\n";
|
||||
request_stream << "Accept: */*\r\n";
|
||||
request_stream << "Connection: close\r\n\r\n";
|
||||
|
||||
// Send the request.
|
||||
asio::write(socket, request);
|
||||
|
||||
// Read the response status line. The response streambuf will automatically
|
||||
// grow to accommodate the entire line. The growth may be limited by passing
|
||||
// a maximum size to the streambuf constructor.
|
||||
asio::streambuf response;
|
||||
asio::read_until(socket, response, "\r\n");
|
||||
|
||||
// Check that response is OK.
|
||||
std::istream response_stream(&response);
|
||||
std::string http_version;
|
||||
response_stream >> http_version;
|
||||
unsigned int status_code;
|
||||
response_stream >> status_code;
|
||||
std::string status_message;
|
||||
std::getline(response_stream, status_message);
|
||||
if (!response_stream || http_version.substr(0, 5) != "HTTP/")
|
||||
{
|
||||
std::cout << "Invalid response\n";
|
||||
return 1;
|
||||
}
|
||||
if (status_code != 200)
|
||||
{
|
||||
std::cout << "Response returned with status code " << status_code << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Read the response headers, which are terminated by a blank line.
|
||||
asio::read_until(socket, response, "\r\n\r\n");
|
||||
|
||||
// Process the response headers.
|
||||
std::string header;
|
||||
while (std::getline(response_stream, header) && header != "\r")
|
||||
std::cout << header << "\n";
|
||||
std::cout << "\n";
|
||||
|
||||
// Write whatever content we already have to output.
|
||||
if (response.size() > 0)
|
||||
std::cout << &response;
|
||||
|
||||
// Read until EOF, writing data to output as we go.
|
||||
asio::error_code error;
|
||||
while (asio::read(socket, response,
|
||||
asio::transfer_at_least(1), error))
|
||||
std::cout << &response;
|
||||
if (error != asio::error::eof)
|
||||
throw asio::system_error(error);
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cout << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
99
asio/src/examples/cpp03/http/server/connection.cpp
Normal file
99
asio/src/examples/cpp03/http/server/connection.cpp
Normal file
@@ -0,0 +1,99 @@
|
||||
//
|
||||
// connection.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "connection.hpp"
|
||||
#include <vector>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "connection_manager.hpp"
|
||||
#include "request_handler.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
connection::connection(asio::io_context& io_context,
|
||||
connection_manager& manager, request_handler& handler)
|
||||
: socket_(io_context),
|
||||
connection_manager_(manager),
|
||||
request_handler_(handler)
|
||||
{
|
||||
}
|
||||
|
||||
asio::ip::tcp::socket& connection::socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void connection::start()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(buffer_),
|
||||
boost::bind(&connection::handle_read, shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void connection::stop()
|
||||
{
|
||||
socket_.close();
|
||||
}
|
||||
|
||||
void connection::handle_read(const asio::error_code& e,
|
||||
std::size_t bytes_transferred)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
boost::tribool result;
|
||||
boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
|
||||
request_, buffer_.data(), buffer_.data() + bytes_transferred);
|
||||
|
||||
if (result)
|
||||
{
|
||||
request_handler_.handle_request(request_, reply_);
|
||||
asio::async_write(socket_, reply_.to_buffers(),
|
||||
boost::bind(&connection::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else if (!result)
|
||||
{
|
||||
reply_ = reply::stock_reply(reply::bad_request);
|
||||
asio::async_write(socket_, reply_.to_buffers(),
|
||||
boost::bind(&connection::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(buffer_),
|
||||
boost::bind(&connection::handle_read, shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
else if (e != asio::error::operation_aborted)
|
||||
{
|
||||
connection_manager_.stop(shared_from_this());
|
||||
}
|
||||
}
|
||||
|
||||
void connection::handle_write(const asio::error_code& e)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
// Initiate graceful connection closure.
|
||||
asio::error_code ignored_ec;
|
||||
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec);
|
||||
}
|
||||
|
||||
if (e != asio::error::operation_aborted)
|
||||
{
|
||||
connection_manager_.stop(shared_from_this());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
83
asio/src/examples/cpp03/http/server/connection.hpp
Normal file
83
asio/src/examples/cpp03/http/server/connection.hpp
Normal file
@@ -0,0 +1,83 @@
|
||||
//
|
||||
// connection.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_CONNECTION_HPP
|
||||
#define HTTP_CONNECTION_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
#include "request_handler.hpp"
|
||||
#include "request_parser.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
class connection_manager;
|
||||
|
||||
/// Represents a single connection from a client.
|
||||
class connection
|
||||
: public boost::enable_shared_from_this<connection>,
|
||||
private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct a connection with the given io_context.
|
||||
explicit connection(asio::io_context& io_context,
|
||||
connection_manager& manager, request_handler& handler);
|
||||
|
||||
/// Get the socket associated with the connection.
|
||||
asio::ip::tcp::socket& socket();
|
||||
|
||||
/// Start the first asynchronous operation for the connection.
|
||||
void start();
|
||||
|
||||
/// Stop all asynchronous operations associated with the connection.
|
||||
void stop();
|
||||
|
||||
private:
|
||||
/// Handle completion of a read operation.
|
||||
void handle_read(const asio::error_code& e,
|
||||
std::size_t bytes_transferred);
|
||||
|
||||
/// Handle completion of a write operation.
|
||||
void handle_write(const asio::error_code& e);
|
||||
|
||||
/// Socket for the connection.
|
||||
asio::ip::tcp::socket socket_;
|
||||
|
||||
/// The manager for this connection.
|
||||
connection_manager& connection_manager_;
|
||||
|
||||
/// The handler used to process the incoming request.
|
||||
request_handler& request_handler_;
|
||||
|
||||
/// Buffer for incoming data.
|
||||
boost::array<char, 8192> buffer_;
|
||||
|
||||
/// The incoming request.
|
||||
request request_;
|
||||
|
||||
/// The parser for the incoming request.
|
||||
request_parser request_parser_;
|
||||
|
||||
/// The reply to be sent back to the client.
|
||||
reply reply_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<connection> connection_ptr;
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_CONNECTION_HPP
|
||||
38
asio/src/examples/cpp03/http/server/connection_manager.cpp
Normal file
38
asio/src/examples/cpp03/http/server/connection_manager.cpp
Normal file
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// connection_manager.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "connection_manager.hpp"
|
||||
#include <algorithm>
|
||||
#include <boost/bind/bind.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
void connection_manager::start(connection_ptr c)
|
||||
{
|
||||
connections_.insert(c);
|
||||
c->start();
|
||||
}
|
||||
|
||||
void connection_manager::stop(connection_ptr c)
|
||||
{
|
||||
connections_.erase(c);
|
||||
c->stop();
|
||||
}
|
||||
|
||||
void connection_manager::stop_all()
|
||||
{
|
||||
std::for_each(connections_.begin(), connections_.end(),
|
||||
boost::bind(&connection::stop, boost::placeholders::_1));
|
||||
connections_.clear();
|
||||
}
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
44
asio/src/examples/cpp03/http/server/connection_manager.hpp
Normal file
44
asio/src/examples/cpp03/http/server/connection_manager.hpp
Normal file
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// connection_manager.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_CONNECTION_MANAGER_HPP
|
||||
#define HTTP_CONNECTION_MANAGER_HPP
|
||||
|
||||
#include <set>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include "connection.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
/// Manages open connections so that they may be cleanly stopped when the server
|
||||
/// needs to shut down.
|
||||
class connection_manager
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Add the specified connection to the manager and start it.
|
||||
void start(connection_ptr c);
|
||||
|
||||
/// Stop the specified connection.
|
||||
void stop(connection_ptr c);
|
||||
|
||||
/// Stop all connections.
|
||||
void stop_all();
|
||||
|
||||
private:
|
||||
/// The managed connections.
|
||||
std::set<connection_ptr> connections_;
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_CONNECTION_MANAGER_HPP
|
||||
28
asio/src/examples/cpp03/http/server/header.hpp
Normal file
28
asio/src/examples/cpp03/http/server/header.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// header.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_HEADER_HPP
|
||||
#define HTTP_HEADER_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
struct header
|
||||
{
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_HEADER_HPP
|
||||
44
asio/src/examples/cpp03/http/server/main.cpp
Normal file
44
asio/src/examples/cpp03/http/server/main.cpp
Normal file
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// main.cpp
|
||||
// ~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "server.hpp"
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check command line arguments.
|
||||
if (argc != 4)
|
||||
{
|
||||
std::cerr << "Usage: http_server <address> <port> <doc_root>\n";
|
||||
std::cerr << " For IPv4, try:\n";
|
||||
std::cerr << " receiver 0.0.0.0 80 .\n";
|
||||
std::cerr << " For IPv6, try:\n";
|
||||
std::cerr << " receiver 0::0 80 .\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Initialise the server.
|
||||
http::server::server s(argv[1], argv[2], argv[3]);
|
||||
|
||||
// Run the server until stopped.
|
||||
s.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
46
asio/src/examples/cpp03/http/server/mime_types.cpp
Normal file
46
asio/src/examples/cpp03/http/server/mime_types.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// mime_types.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "mime_types.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
namespace mime_types {
|
||||
|
||||
struct mapping
|
||||
{
|
||||
const char* extension;
|
||||
const char* mime_type;
|
||||
} mappings[] =
|
||||
{
|
||||
{ "gif", "image/gif" },
|
||||
{ "htm", "text/html" },
|
||||
{ "html", "text/html" },
|
||||
{ "jpg", "image/jpeg" },
|
||||
{ "png", "image/png" },
|
||||
{ 0, 0 } // Marks end of list.
|
||||
};
|
||||
|
||||
std::string extension_to_type(const std::string& extension)
|
||||
{
|
||||
for (mapping* m = mappings; m->extension; ++m)
|
||||
{
|
||||
if (m->extension == extension)
|
||||
{
|
||||
return m->mime_type;
|
||||
}
|
||||
}
|
||||
|
||||
return "text/plain";
|
||||
}
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
27
asio/src/examples/cpp03/http/server/mime_types.hpp
Normal file
27
asio/src/examples/cpp03/http/server/mime_types.hpp
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// mime_types.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_MIME_TYPES_HPP
|
||||
#define HTTP_MIME_TYPES_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
namespace mime_types {
|
||||
|
||||
/// Convert a file extension into a MIME type.
|
||||
std::string extension_to_type(const std::string& extension);
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_MIME_TYPES_HPP
|
||||
256
asio/src/examples/cpp03/http/server/reply.cpp
Normal file
256
asio/src/examples/cpp03/http/server/reply.cpp
Normal file
@@ -0,0 +1,256 @@
|
||||
//
|
||||
// reply.cpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "reply.hpp"
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
namespace status_strings {
|
||||
|
||||
const std::string ok =
|
||||
"HTTP/1.0 200 OK\r\n";
|
||||
const std::string created =
|
||||
"HTTP/1.0 201 Created\r\n";
|
||||
const std::string accepted =
|
||||
"HTTP/1.0 202 Accepted\r\n";
|
||||
const std::string no_content =
|
||||
"HTTP/1.0 204 No Content\r\n";
|
||||
const std::string multiple_choices =
|
||||
"HTTP/1.0 300 Multiple Choices\r\n";
|
||||
const std::string moved_permanently =
|
||||
"HTTP/1.0 301 Moved Permanently\r\n";
|
||||
const std::string moved_temporarily =
|
||||
"HTTP/1.0 302 Moved Temporarily\r\n";
|
||||
const std::string not_modified =
|
||||
"HTTP/1.0 304 Not Modified\r\n";
|
||||
const std::string bad_request =
|
||||
"HTTP/1.0 400 Bad Request\r\n";
|
||||
const std::string unauthorized =
|
||||
"HTTP/1.0 401 Unauthorized\r\n";
|
||||
const std::string forbidden =
|
||||
"HTTP/1.0 403 Forbidden\r\n";
|
||||
const std::string not_found =
|
||||
"HTTP/1.0 404 Not Found\r\n";
|
||||
const std::string internal_server_error =
|
||||
"HTTP/1.0 500 Internal Server Error\r\n";
|
||||
const std::string not_implemented =
|
||||
"HTTP/1.0 501 Not Implemented\r\n";
|
||||
const std::string bad_gateway =
|
||||
"HTTP/1.0 502 Bad Gateway\r\n";
|
||||
const std::string service_unavailable =
|
||||
"HTTP/1.0 503 Service Unavailable\r\n";
|
||||
|
||||
asio::const_buffer to_buffer(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return asio::buffer(ok);
|
||||
case reply::created:
|
||||
return asio::buffer(created);
|
||||
case reply::accepted:
|
||||
return asio::buffer(accepted);
|
||||
case reply::no_content:
|
||||
return asio::buffer(no_content);
|
||||
case reply::multiple_choices:
|
||||
return asio::buffer(multiple_choices);
|
||||
case reply::moved_permanently:
|
||||
return asio::buffer(moved_permanently);
|
||||
case reply::moved_temporarily:
|
||||
return asio::buffer(moved_temporarily);
|
||||
case reply::not_modified:
|
||||
return asio::buffer(not_modified);
|
||||
case reply::bad_request:
|
||||
return asio::buffer(bad_request);
|
||||
case reply::unauthorized:
|
||||
return asio::buffer(unauthorized);
|
||||
case reply::forbidden:
|
||||
return asio::buffer(forbidden);
|
||||
case reply::not_found:
|
||||
return asio::buffer(not_found);
|
||||
case reply::internal_server_error:
|
||||
return asio::buffer(internal_server_error);
|
||||
case reply::not_implemented:
|
||||
return asio::buffer(not_implemented);
|
||||
case reply::bad_gateway:
|
||||
return asio::buffer(bad_gateway);
|
||||
case reply::service_unavailable:
|
||||
return asio::buffer(service_unavailable);
|
||||
default:
|
||||
return asio::buffer(internal_server_error);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace status_strings
|
||||
|
||||
namespace misc_strings {
|
||||
|
||||
const char name_value_separator[] = { ':', ' ' };
|
||||
const char crlf[] = { '\r', '\n' };
|
||||
|
||||
} // namespace misc_strings
|
||||
|
||||
std::vector<asio::const_buffer> reply::to_buffers()
|
||||
{
|
||||
std::vector<asio::const_buffer> buffers;
|
||||
buffers.push_back(status_strings::to_buffer(status));
|
||||
for (std::size_t i = 0; i < headers.size(); ++i)
|
||||
{
|
||||
header& h = headers[i];
|
||||
buffers.push_back(asio::buffer(h.name));
|
||||
buffers.push_back(asio::buffer(misc_strings::name_value_separator));
|
||||
buffers.push_back(asio::buffer(h.value));
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
}
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
buffers.push_back(asio::buffer(content));
|
||||
return buffers;
|
||||
}
|
||||
|
||||
namespace stock_replies {
|
||||
|
||||
const char ok[] = "";
|
||||
const char created[] =
|
||||
"<html>"
|
||||
"<head><title>Created</title></head>"
|
||||
"<body><h1>201 Created</h1></body>"
|
||||
"</html>";
|
||||
const char accepted[] =
|
||||
"<html>"
|
||||
"<head><title>Accepted</title></head>"
|
||||
"<body><h1>202 Accepted</h1></body>"
|
||||
"</html>";
|
||||
const char no_content[] =
|
||||
"<html>"
|
||||
"<head><title>No Content</title></head>"
|
||||
"<body><h1>204 Content</h1></body>"
|
||||
"</html>";
|
||||
const char multiple_choices[] =
|
||||
"<html>"
|
||||
"<head><title>Multiple Choices</title></head>"
|
||||
"<body><h1>300 Multiple Choices</h1></body>"
|
||||
"</html>";
|
||||
const char moved_permanently[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Permanently</title></head>"
|
||||
"<body><h1>301 Moved Permanently</h1></body>"
|
||||
"</html>";
|
||||
const char moved_temporarily[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Temporarily</title></head>"
|
||||
"<body><h1>302 Moved Temporarily</h1></body>"
|
||||
"</html>";
|
||||
const char not_modified[] =
|
||||
"<html>"
|
||||
"<head><title>Not Modified</title></head>"
|
||||
"<body><h1>304 Not Modified</h1></body>"
|
||||
"</html>";
|
||||
const char bad_request[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Request</title></head>"
|
||||
"<body><h1>400 Bad Request</h1></body>"
|
||||
"</html>";
|
||||
const char unauthorized[] =
|
||||
"<html>"
|
||||
"<head><title>Unauthorized</title></head>"
|
||||
"<body><h1>401 Unauthorized</h1></body>"
|
||||
"</html>";
|
||||
const char forbidden[] =
|
||||
"<html>"
|
||||
"<head><title>Forbidden</title></head>"
|
||||
"<body><h1>403 Forbidden</h1></body>"
|
||||
"</html>";
|
||||
const char not_found[] =
|
||||
"<html>"
|
||||
"<head><title>Not Found</title></head>"
|
||||
"<body><h1>404 Not Found</h1></body>"
|
||||
"</html>";
|
||||
const char internal_server_error[] =
|
||||
"<html>"
|
||||
"<head><title>Internal Server Error</title></head>"
|
||||
"<body><h1>500 Internal Server Error</h1></body>"
|
||||
"</html>";
|
||||
const char not_implemented[] =
|
||||
"<html>"
|
||||
"<head><title>Not Implemented</title></head>"
|
||||
"<body><h1>501 Not Implemented</h1></body>"
|
||||
"</html>";
|
||||
const char bad_gateway[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Gateway</title></head>"
|
||||
"<body><h1>502 Bad Gateway</h1></body>"
|
||||
"</html>";
|
||||
const char service_unavailable[] =
|
||||
"<html>"
|
||||
"<head><title>Service Unavailable</title></head>"
|
||||
"<body><h1>503 Service Unavailable</h1></body>"
|
||||
"</html>";
|
||||
|
||||
std::string to_string(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return ok;
|
||||
case reply::created:
|
||||
return created;
|
||||
case reply::accepted:
|
||||
return accepted;
|
||||
case reply::no_content:
|
||||
return no_content;
|
||||
case reply::multiple_choices:
|
||||
return multiple_choices;
|
||||
case reply::moved_permanently:
|
||||
return moved_permanently;
|
||||
case reply::moved_temporarily:
|
||||
return moved_temporarily;
|
||||
case reply::not_modified:
|
||||
return not_modified;
|
||||
case reply::bad_request:
|
||||
return bad_request;
|
||||
case reply::unauthorized:
|
||||
return unauthorized;
|
||||
case reply::forbidden:
|
||||
return forbidden;
|
||||
case reply::not_found:
|
||||
return not_found;
|
||||
case reply::internal_server_error:
|
||||
return internal_server_error;
|
||||
case reply::not_implemented:
|
||||
return not_implemented;
|
||||
case reply::bad_gateway:
|
||||
return bad_gateway;
|
||||
case reply::service_unavailable:
|
||||
return service_unavailable;
|
||||
default:
|
||||
return internal_server_error;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace stock_replies
|
||||
|
||||
reply reply::stock_reply(reply::status_type status)
|
||||
{
|
||||
reply rep;
|
||||
rep.status = status;
|
||||
rep.content = stock_replies::to_string(status);
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = "text/html";
|
||||
return rep;
|
||||
}
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
64
asio/src/examples/cpp03/http/server/reply.hpp
Normal file
64
asio/src/examples/cpp03/http/server/reply.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// reply.hpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_REPLY_HPP
|
||||
#define HTTP_REPLY_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <asio.hpp>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
/// A reply to be sent to a client.
|
||||
struct reply
|
||||
{
|
||||
/// The status of the reply.
|
||||
enum status_type
|
||||
{
|
||||
ok = 200,
|
||||
created = 201,
|
||||
accepted = 202,
|
||||
no_content = 204,
|
||||
multiple_choices = 300,
|
||||
moved_permanently = 301,
|
||||
moved_temporarily = 302,
|
||||
not_modified = 304,
|
||||
bad_request = 400,
|
||||
unauthorized = 401,
|
||||
forbidden = 403,
|
||||
not_found = 404,
|
||||
internal_server_error = 500,
|
||||
not_implemented = 501,
|
||||
bad_gateway = 502,
|
||||
service_unavailable = 503
|
||||
} status;
|
||||
|
||||
/// The headers to be included in the reply.
|
||||
std::vector<header> headers;
|
||||
|
||||
/// The content to be sent in the reply.
|
||||
std::string content;
|
||||
|
||||
/// Convert the reply into a vector of buffers. The buffers do not own the
|
||||
/// underlying memory blocks, therefore the reply object must remain valid and
|
||||
/// not be changed until the write operation has completed.
|
||||
std::vector<asio::const_buffer> to_buffers();
|
||||
|
||||
/// Get a stock reply.
|
||||
static reply stock_reply(status_type status);
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_REPLY_HPP
|
||||
34
asio/src/examples/cpp03/http/server/request.hpp
Normal file
34
asio/src/examples/cpp03/http/server/request.hpp
Normal file
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// request.hpp
|
||||
// ~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_REQUEST_HPP
|
||||
#define HTTP_REQUEST_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
/// A request received from a client.
|
||||
struct request
|
||||
{
|
||||
std::string method;
|
||||
std::string uri;
|
||||
int http_version_major;
|
||||
int http_version_minor;
|
||||
std::vector<header> headers;
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_REQUEST_HPP
|
||||
122
asio/src/examples/cpp03/http/server/request_handler.cpp
Normal file
122
asio/src/examples/cpp03/http/server/request_handler.cpp
Normal file
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// request_handler.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_handler.hpp"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "mime_types.hpp"
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
request_handler::request_handler(const std::string& doc_root)
|
||||
: doc_root_(doc_root)
|
||||
{
|
||||
}
|
||||
|
||||
void request_handler::handle_request(const request& req, reply& rep)
|
||||
{
|
||||
// Decode url to path.
|
||||
std::string request_path;
|
||||
if (!url_decode(req.uri, request_path))
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// Request path must be absolute and not contain "..".
|
||||
if (request_path.empty() || request_path[0] != '/'
|
||||
|| request_path.find("..") != std::string::npos)
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// If path ends in slash (i.e. is a directory) then add "index.html".
|
||||
if (request_path[request_path.size() - 1] == '/')
|
||||
{
|
||||
request_path += "index.html";
|
||||
}
|
||||
|
||||
// Determine the file extension.
|
||||
std::size_t last_slash_pos = request_path.find_last_of("/");
|
||||
std::size_t last_dot_pos = request_path.find_last_of(".");
|
||||
std::string extension;
|
||||
if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos)
|
||||
{
|
||||
extension = request_path.substr(last_dot_pos + 1);
|
||||
}
|
||||
|
||||
// Open the file to send back.
|
||||
std::string full_path = doc_root_ + request_path;
|
||||
std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
|
||||
if (!is)
|
||||
{
|
||||
rep = reply::stock_reply(reply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill out the reply to be sent to the client.
|
||||
rep.status = reply::ok;
|
||||
char buf[512];
|
||||
while (is.read(buf, sizeof(buf)).gcount() > 0)
|
||||
rep.content.append(buf, is.gcount());
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = mime_types::extension_to_type(extension);
|
||||
}
|
||||
|
||||
bool request_handler::url_decode(const std::string& in, std::string& out)
|
||||
{
|
||||
out.clear();
|
||||
out.reserve(in.size());
|
||||
for (std::size_t i = 0; i < in.size(); ++i)
|
||||
{
|
||||
if (in[i] == '%')
|
||||
{
|
||||
if (i + 3 <= in.size())
|
||||
{
|
||||
int value = 0;
|
||||
std::istringstream is(in.substr(i + 1, 2));
|
||||
if (is >> std::hex >> value)
|
||||
{
|
||||
out += static_cast<char>(value);
|
||||
i += 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (in[i] == '+')
|
||||
{
|
||||
out += ' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
out += in[i];
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
46
asio/src/examples/cpp03/http/server/request_handler.hpp
Normal file
46
asio/src/examples/cpp03/http/server/request_handler.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// request_handler.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_REQUEST_HANDLER_HPP
|
||||
#define HTTP_REQUEST_HANDLER_HPP
|
||||
|
||||
#include <string>
|
||||
#include <boost/noncopyable.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
struct reply;
|
||||
struct request;
|
||||
|
||||
/// The common handler for all incoming requests.
|
||||
class request_handler
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct with a directory containing files to be served.
|
||||
explicit request_handler(const std::string& doc_root);
|
||||
|
||||
/// Handle a request and produce a reply.
|
||||
void handle_request(const request& req, reply& rep);
|
||||
|
||||
private:
|
||||
/// The directory containing the files to be served.
|
||||
std::string doc_root_;
|
||||
|
||||
/// Perform URL-decoding on a string. Returns false if the encoding was
|
||||
/// invalid.
|
||||
static bool url_decode(const std::string& in, std::string& out);
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_REQUEST_HANDLER_HPP
|
||||
315
asio/src/examples/cpp03/http/server/request_parser.cpp
Normal file
315
asio/src/examples/cpp03/http/server/request_parser.cpp
Normal file
@@ -0,0 +1,315 @@
|
||||
//
|
||||
// request_parser.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_parser.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
request_parser::request_parser()
|
||||
: state_(method_start)
|
||||
{
|
||||
}
|
||||
|
||||
void request_parser::reset()
|
||||
{
|
||||
state_ = method_start;
|
||||
}
|
||||
|
||||
boost::tribool request_parser::consume(request& req, char input)
|
||||
{
|
||||
switch (state_)
|
||||
{
|
||||
case method_start:
|
||||
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = method;
|
||||
req.method.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case method:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = uri;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.method.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case uri:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = http_version_h;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.uri.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case http_version_h:
|
||||
if (input == 'H')
|
||||
{
|
||||
state_ = http_version_t_1;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_t_1:
|
||||
if (input == 'T')
|
||||
{
|
||||
state_ = http_version_t_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_t_2:
|
||||
if (input == 'T')
|
||||
{
|
||||
state_ = http_version_p;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_p:
|
||||
if (input == 'P')
|
||||
{
|
||||
state_ = http_version_slash;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_slash:
|
||||
if (input == '/')
|
||||
{
|
||||
req.http_version_major = 0;
|
||||
req.http_version_minor = 0;
|
||||
state_ = http_version_major_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_major_start:
|
||||
if (is_digit(input))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + input - '0';
|
||||
state_ = http_version_major;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_major:
|
||||
if (input == '.')
|
||||
{
|
||||
state_ = http_version_minor_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_digit(input))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + input - '0';
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_minor_start:
|
||||
if (is_digit(input))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + input - '0';
|
||||
state_ = http_version_minor;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_minor:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_1;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_digit(input))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + input - '0';
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case expecting_newline_1:
|
||||
if (input == '\n')
|
||||
{
|
||||
state_ = header_line_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case header_line_start:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_3;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!req.headers.empty() && (input == ' ' || input == '\t'))
|
||||
{
|
||||
state_ = header_lws;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.push_back(header());
|
||||
req.headers.back().name.push_back(input);
|
||||
state_ = header_name;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case header_lws:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (input == ' ' || input == '\t')
|
||||
{
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = header_value;
|
||||
req.headers.back().value.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case header_name:
|
||||
if (input == ':')
|
||||
{
|
||||
state_ = space_before_header_value;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.back().name.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case space_before_header_value:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = header_value;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case header_value:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.back().value.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case expecting_newline_2:
|
||||
if (input == '\n')
|
||||
{
|
||||
state_ = header_line_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case expecting_newline_3:
|
||||
return (input == '\n');
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_char(int c)
|
||||
{
|
||||
return c >= 0 && c <= 127;
|
||||
}
|
||||
|
||||
bool request_parser::is_ctl(int c)
|
||||
{
|
||||
return (c >= 0 && c <= 31) || (c == 127);
|
||||
}
|
||||
|
||||
bool request_parser::is_tspecial(int c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '(': case ')': case '<': case '>': case '@':
|
||||
case ',': case ';': case ':': case '\\': case '"':
|
||||
case '/': case '[': case ']': case '?': case '=':
|
||||
case '{': case '}': case ' ': case '\t':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_digit(int c)
|
||||
{
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
95
asio/src/examples/cpp03/http/server/request_parser.hpp
Normal file
95
asio/src/examples/cpp03/http/server/request_parser.hpp
Normal file
@@ -0,0 +1,95 @@
|
||||
//
|
||||
// request_parser.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_REQUEST_PARSER_HPP
|
||||
#define HTTP_REQUEST_PARSER_HPP
|
||||
|
||||
#include <boost/logic/tribool.hpp>
|
||||
#include <boost/tuple/tuple.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
struct request;
|
||||
|
||||
/// Parser for incoming requests.
|
||||
class request_parser
|
||||
{
|
||||
public:
|
||||
/// Construct ready to parse the request method.
|
||||
request_parser();
|
||||
|
||||
/// Reset to initial parser state.
|
||||
void reset();
|
||||
|
||||
/// Parse some data. The tribool return value is true when a complete request
|
||||
/// has been parsed, false if the data is invalid, indeterminate when more
|
||||
/// data is required. The InputIterator return value indicates how much of the
|
||||
/// input has been consumed.
|
||||
template <typename InputIterator>
|
||||
boost::tuple<boost::tribool, InputIterator> parse(request& req,
|
||||
InputIterator begin, InputIterator end)
|
||||
{
|
||||
while (begin != end)
|
||||
{
|
||||
boost::tribool result = consume(req, *begin++);
|
||||
if (result || !result)
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
boost::tribool result = boost::indeterminate;
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
|
||||
private:
|
||||
/// Handle the next character of input.
|
||||
boost::tribool consume(request& req, char input);
|
||||
|
||||
/// Check if a byte is an HTTP character.
|
||||
static bool is_char(int c);
|
||||
|
||||
/// Check if a byte is an HTTP control character.
|
||||
static bool is_ctl(int c);
|
||||
|
||||
/// Check if a byte is defined as an HTTP tspecial character.
|
||||
static bool is_tspecial(int c);
|
||||
|
||||
/// Check if a byte is a digit.
|
||||
static bool is_digit(int c);
|
||||
|
||||
/// The current state of the parser.
|
||||
enum state
|
||||
{
|
||||
method_start,
|
||||
method,
|
||||
uri,
|
||||
http_version_h,
|
||||
http_version_t_1,
|
||||
http_version_t_2,
|
||||
http_version_p,
|
||||
http_version_slash,
|
||||
http_version_major_start,
|
||||
http_version_major,
|
||||
http_version_minor_start,
|
||||
http_version_minor,
|
||||
expecting_newline_1,
|
||||
header_line_start,
|
||||
header_lws,
|
||||
header_name,
|
||||
space_before_header_value,
|
||||
header_value,
|
||||
expecting_newline_2,
|
||||
expecting_newline_3
|
||||
} state_;
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_REQUEST_PARSER_HPP
|
||||
94
asio/src/examples/cpp03/http/server/server.cpp
Normal file
94
asio/src/examples/cpp03/http/server/server.cpp
Normal file
@@ -0,0 +1,94 @@
|
||||
//
|
||||
// server.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "server.hpp"
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <signal.h>
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
server::server(const std::string& address, const std::string& port,
|
||||
const std::string& doc_root)
|
||||
: io_context_(),
|
||||
signals_(io_context_),
|
||||
acceptor_(io_context_),
|
||||
connection_manager_(),
|
||||
new_connection_(),
|
||||
request_handler_(doc_root)
|
||||
{
|
||||
// Register to handle the signals that indicate when the server should exit.
|
||||
// It is safe to register for the same signal multiple times in a program,
|
||||
// provided all registration for the specified signal is made through Asio.
|
||||
signals_.add(SIGINT);
|
||||
signals_.add(SIGTERM);
|
||||
#if defined(SIGQUIT)
|
||||
signals_.add(SIGQUIT);
|
||||
#endif // defined(SIGQUIT)
|
||||
signals_.async_wait(boost::bind(&server::handle_stop, this));
|
||||
|
||||
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
|
||||
asio::ip::tcp::resolver resolver(io_context_);
|
||||
asio::ip::tcp::endpoint endpoint =
|
||||
*resolver.resolve(address, port).begin();
|
||||
acceptor_.open(endpoint.protocol());
|
||||
acceptor_.set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
||||
acceptor_.bind(endpoint);
|
||||
acceptor_.listen();
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void server::run()
|
||||
{
|
||||
// The io_context::run() call will block until all asynchronous operations
|
||||
// have finished. While the server is running, there is always at least one
|
||||
// asynchronous operation outstanding: the asynchronous accept call waiting
|
||||
// for new incoming connections.
|
||||
io_context_.run();
|
||||
}
|
||||
|
||||
void server::start_accept()
|
||||
{
|
||||
new_connection_.reset(new connection(io_context_,
|
||||
connection_manager_, request_handler_));
|
||||
acceptor_.async_accept(new_connection_->socket(),
|
||||
boost::bind(&server::handle_accept, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void server::handle_accept(const asio::error_code& e)
|
||||
{
|
||||
// Check whether the server was stopped by a signal before this completion
|
||||
// handler had a chance to run.
|
||||
if (!acceptor_.is_open())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!e)
|
||||
{
|
||||
connection_manager_.start(new_connection_);
|
||||
}
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void server::handle_stop()
|
||||
{
|
||||
// The server is stopped by cancelling all outstanding asynchronous
|
||||
// operations. Once all operations have finished the io_context::run() call
|
||||
// will exit.
|
||||
acceptor_.close();
|
||||
connection_manager_.stop_all();
|
||||
}
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
69
asio/src/examples/cpp03/http/server/server.hpp
Normal file
69
asio/src/examples/cpp03/http/server/server.hpp
Normal file
@@ -0,0 +1,69 @@
|
||||
//
|
||||
// server.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER_HPP
|
||||
#define HTTP_SERVER_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <string>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include "connection.hpp"
|
||||
#include "connection_manager.hpp"
|
||||
#include "request_handler.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server {
|
||||
|
||||
/// The top-level class of the HTTP server.
|
||||
class server
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct the server to listen on the specified TCP address and port, and
|
||||
/// serve up files from the given directory.
|
||||
explicit server(const std::string& address, const std::string& port,
|
||||
const std::string& doc_root);
|
||||
|
||||
/// Run the server's io_context loop.
|
||||
void run();
|
||||
|
||||
private:
|
||||
/// Initiate an asynchronous accept operation.
|
||||
void start_accept();
|
||||
|
||||
/// Handle completion of an asynchronous accept operation.
|
||||
void handle_accept(const asio::error_code& e);
|
||||
|
||||
/// Handle a request to stop the server.
|
||||
void handle_stop();
|
||||
|
||||
/// The io_context used to perform asynchronous operations.
|
||||
asio::io_context io_context_;
|
||||
|
||||
/// The signal_set is used to register for process termination notifications.
|
||||
asio::signal_set signals_;
|
||||
|
||||
/// Acceptor used to listen for incoming connections.
|
||||
asio::ip::tcp::acceptor acceptor_;
|
||||
|
||||
/// The connection manager which owns all live connections.
|
||||
connection_manager connection_manager_;
|
||||
|
||||
/// The next connection to be accepted.
|
||||
connection_ptr new_connection_;
|
||||
|
||||
/// The handler for all incoming requests.
|
||||
request_handler request_handler_;
|
||||
};
|
||||
|
||||
} // namespace server
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER_HPP
|
||||
93
asio/src/examples/cpp03/http/server2/connection.cpp
Normal file
93
asio/src/examples/cpp03/http/server2/connection.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// connection.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "connection.hpp"
|
||||
#include <vector>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "request_handler.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
connection::connection(asio::io_context& io_context,
|
||||
request_handler& handler)
|
||||
: socket_(io_context),
|
||||
request_handler_(handler)
|
||||
{
|
||||
}
|
||||
|
||||
asio::ip::tcp::socket& connection::socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void connection::start()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(buffer_),
|
||||
boost::bind(&connection::handle_read, shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void connection::handle_read(const asio::error_code& e,
|
||||
std::size_t bytes_transferred)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
boost::tribool result;
|
||||
boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
|
||||
request_, buffer_.data(), buffer_.data() + bytes_transferred);
|
||||
|
||||
if (result)
|
||||
{
|
||||
request_handler_.handle_request(request_, reply_);
|
||||
asio::async_write(socket_, reply_.to_buffers(),
|
||||
boost::bind(&connection::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else if (!result)
|
||||
{
|
||||
reply_ = reply::stock_reply(reply::bad_request);
|
||||
asio::async_write(socket_, reply_.to_buffers(),
|
||||
boost::bind(&connection::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(buffer_),
|
||||
boost::bind(&connection::handle_read, shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
|
||||
// If an error occurs then no new asynchronous operations are started. This
|
||||
// means that all shared_ptr references to the connection object will
|
||||
// disappear and the object will be destroyed automatically after this
|
||||
// handler returns. The connection class's destructor closes the socket.
|
||||
}
|
||||
|
||||
void connection::handle_write(const asio::error_code& e)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
// Initiate graceful connection closure.
|
||||
asio::error_code ignored_ec;
|
||||
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec);
|
||||
}
|
||||
|
||||
// No new asynchronous operations are started. This means that all shared_ptr
|
||||
// references to the connection object will disappear and the object will be
|
||||
// destroyed automatically after this handler returns. The connection class's
|
||||
// destructor closes the socket.
|
||||
}
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
75
asio/src/examples/cpp03/http/server2/connection.hpp
Normal file
75
asio/src/examples/cpp03/http/server2/connection.hpp
Normal file
@@ -0,0 +1,75 @@
|
||||
//
|
||||
// connection.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_CONNECTION_HPP
|
||||
#define HTTP_SERVER2_CONNECTION_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
#include "request_handler.hpp"
|
||||
#include "request_parser.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
/// Represents a single connection from a client.
|
||||
class connection
|
||||
: public boost::enable_shared_from_this<connection>,
|
||||
private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct a connection with the given io_context.
|
||||
explicit connection(asio::io_context& io_context,
|
||||
request_handler& handler);
|
||||
|
||||
/// Get the socket associated with the connection.
|
||||
asio::ip::tcp::socket& socket();
|
||||
|
||||
/// Start the first asynchronous operation for the connection.
|
||||
void start();
|
||||
|
||||
private:
|
||||
/// Handle completion of a read operation.
|
||||
void handle_read(const asio::error_code& e,
|
||||
std::size_t bytes_transferred);
|
||||
|
||||
/// Handle completion of a write operation.
|
||||
void handle_write(const asio::error_code& e);
|
||||
|
||||
/// Socket for the connection.
|
||||
asio::ip::tcp::socket socket_;
|
||||
|
||||
/// The handler used to process the incoming request.
|
||||
request_handler& request_handler_;
|
||||
|
||||
/// Buffer for incoming data.
|
||||
boost::array<char, 8192> buffer_;
|
||||
|
||||
/// The incoming request.
|
||||
request request_;
|
||||
|
||||
/// The parser for the incoming request.
|
||||
request_parser request_parser_;
|
||||
|
||||
/// The reply to be sent back to the client.
|
||||
reply reply_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<connection> connection_ptr;
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_CONNECTION_HPP
|
||||
28
asio/src/examples/cpp03/http/server2/header.hpp
Normal file
28
asio/src/examples/cpp03/http/server2/header.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// header.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_HEADER_HPP
|
||||
#define HTTP_SERVER2_HEADER_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
struct header
|
||||
{
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_HEADER_HPP
|
||||
70
asio/src/examples/cpp03/http/server2/io_context_pool.cpp
Normal file
70
asio/src/examples/cpp03/http/server2/io_context_pool.cpp
Normal file
@@ -0,0 +1,70 @@
|
||||
//
|
||||
// io_context_pool.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "server.hpp"
|
||||
#include <stdexcept>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
io_context_pool::io_context_pool(std::size_t pool_size)
|
||||
: next_io_context_(0)
|
||||
{
|
||||
if (pool_size == 0)
|
||||
throw std::runtime_error("io_context_pool size is 0");
|
||||
|
||||
// Give all the io_contexts work to do so that their run() functions will not
|
||||
// exit until they are explicitly stopped.
|
||||
for (std::size_t i = 0; i < pool_size; ++i)
|
||||
{
|
||||
io_context_ptr io_context(new asio::io_context);
|
||||
io_contexts_.push_back(io_context);
|
||||
work_.push_back(asio::require(io_context->get_executor(),
|
||||
asio::execution::outstanding_work.tracked));
|
||||
}
|
||||
}
|
||||
|
||||
void io_context_pool::run()
|
||||
{
|
||||
// Create a pool of threads to run all of the io_contexts.
|
||||
std::vector<boost::shared_ptr<asio::thread> > threads;
|
||||
for (std::size_t i = 0; i < io_contexts_.size(); ++i)
|
||||
{
|
||||
boost::shared_ptr<asio::thread> thread(new asio::thread(
|
||||
boost::bind(&asio::io_context::run, io_contexts_[i])));
|
||||
threads.push_back(thread);
|
||||
}
|
||||
|
||||
// Wait for all threads in the pool to exit.
|
||||
for (std::size_t i = 0; i < threads.size(); ++i)
|
||||
threads[i]->join();
|
||||
}
|
||||
|
||||
void io_context_pool::stop()
|
||||
{
|
||||
// Explicitly stop all io_contexts.
|
||||
for (std::size_t i = 0; i < io_contexts_.size(); ++i)
|
||||
io_contexts_[i]->stop();
|
||||
}
|
||||
|
||||
asio::io_context& io_context_pool::get_io_context()
|
||||
{
|
||||
// Use a round-robin scheme to choose the next io_context to use.
|
||||
asio::io_context& io_context = *io_contexts_[next_io_context_];
|
||||
++next_io_context_;
|
||||
if (next_io_context_ == io_contexts_.size())
|
||||
next_io_context_ = 0;
|
||||
return io_context;
|
||||
}
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
56
asio/src/examples/cpp03/http/server2/io_context_pool.hpp
Normal file
56
asio/src/examples/cpp03/http/server2/io_context_pool.hpp
Normal file
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// io_context_pool.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_IO_SERVICE_POOL_HPP
|
||||
#define HTTP_SERVER2_IO_SERVICE_POOL_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <list>
|
||||
#include <vector>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
/// A pool of io_context objects.
|
||||
class io_context_pool
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct the io_context pool.
|
||||
explicit io_context_pool(std::size_t pool_size);
|
||||
|
||||
/// Run all io_context objects in the pool.
|
||||
void run();
|
||||
|
||||
/// Stop all io_context objects in the pool.
|
||||
void stop();
|
||||
|
||||
/// Get an io_context to use.
|
||||
asio::io_context& get_io_context();
|
||||
|
||||
private:
|
||||
typedef boost::shared_ptr<asio::io_context> io_context_ptr;
|
||||
|
||||
/// The pool of io_contexts.
|
||||
std::vector<io_context_ptr> io_contexts_;
|
||||
|
||||
/// The work-tracking executors that keep the io_contexts running.
|
||||
std::list<asio::any_io_executor> work_;
|
||||
|
||||
/// The next io_context to use for a connection.
|
||||
std::size_t next_io_context_;
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_IO_SERVICE_POOL_HPP
|
||||
46
asio/src/examples/cpp03/http/server2/main.cpp
Normal file
46
asio/src/examples/cpp03/http/server2/main.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// main.cpp
|
||||
// ~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "server.hpp"
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check command line arguments.
|
||||
if (argc != 5)
|
||||
{
|
||||
std::cerr << "Usage: http_server <address> <port> <threads> <doc_root>\n";
|
||||
std::cerr << " For IPv4, try:\n";
|
||||
std::cerr << " receiver 0.0.0.0 80 1 .\n";
|
||||
std::cerr << " For IPv6, try:\n";
|
||||
std::cerr << " receiver 0::0 80 1 .\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Initialise the server.
|
||||
std::size_t num_threads = boost::lexical_cast<std::size_t>(argv[3]);
|
||||
http::server2::server s(argv[1], argv[2], argv[4], num_threads);
|
||||
|
||||
// Run the server until stopped.
|
||||
s.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
46
asio/src/examples/cpp03/http/server2/mime_types.cpp
Normal file
46
asio/src/examples/cpp03/http/server2/mime_types.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// mime_types.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "mime_types.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
namespace mime_types {
|
||||
|
||||
struct mapping
|
||||
{
|
||||
const char* extension;
|
||||
const char* mime_type;
|
||||
} mappings[] =
|
||||
{
|
||||
{ "gif", "image/gif" },
|
||||
{ "htm", "text/html" },
|
||||
{ "html", "text/html" },
|
||||
{ "jpg", "image/jpeg" },
|
||||
{ "png", "image/png" },
|
||||
{ 0, 0 } // Marks end of list.
|
||||
};
|
||||
|
||||
std::string extension_to_type(const std::string& extension)
|
||||
{
|
||||
for (mapping* m = mappings; m->extension; ++m)
|
||||
{
|
||||
if (m->extension == extension)
|
||||
{
|
||||
return m->mime_type;
|
||||
}
|
||||
}
|
||||
|
||||
return "text/plain";
|
||||
}
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
27
asio/src/examples/cpp03/http/server2/mime_types.hpp
Normal file
27
asio/src/examples/cpp03/http/server2/mime_types.hpp
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// mime_types.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_MIME_TYPES_HPP
|
||||
#define HTTP_SERVER2_MIME_TYPES_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
namespace mime_types {
|
||||
|
||||
/// Convert a file extension into a MIME type.
|
||||
std::string extension_to_type(const std::string& extension);
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_MIME_TYPES_HPP
|
||||
256
asio/src/examples/cpp03/http/server2/reply.cpp
Normal file
256
asio/src/examples/cpp03/http/server2/reply.cpp
Normal file
@@ -0,0 +1,256 @@
|
||||
//
|
||||
// reply.cpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "reply.hpp"
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
namespace status_strings {
|
||||
|
||||
const std::string ok =
|
||||
"HTTP/1.0 200 OK\r\n";
|
||||
const std::string created =
|
||||
"HTTP/1.0 201 Created\r\n";
|
||||
const std::string accepted =
|
||||
"HTTP/1.0 202 Accepted\r\n";
|
||||
const std::string no_content =
|
||||
"HTTP/1.0 204 No Content\r\n";
|
||||
const std::string multiple_choices =
|
||||
"HTTP/1.0 300 Multiple Choices\r\n";
|
||||
const std::string moved_permanently =
|
||||
"HTTP/1.0 301 Moved Permanently\r\n";
|
||||
const std::string moved_temporarily =
|
||||
"HTTP/1.0 302 Moved Temporarily\r\n";
|
||||
const std::string not_modified =
|
||||
"HTTP/1.0 304 Not Modified\r\n";
|
||||
const std::string bad_request =
|
||||
"HTTP/1.0 400 Bad Request\r\n";
|
||||
const std::string unauthorized =
|
||||
"HTTP/1.0 401 Unauthorized\r\n";
|
||||
const std::string forbidden =
|
||||
"HTTP/1.0 403 Forbidden\r\n";
|
||||
const std::string not_found =
|
||||
"HTTP/1.0 404 Not Found\r\n";
|
||||
const std::string internal_server_error =
|
||||
"HTTP/1.0 500 Internal Server Error\r\n";
|
||||
const std::string not_implemented =
|
||||
"HTTP/1.0 501 Not Implemented\r\n";
|
||||
const std::string bad_gateway =
|
||||
"HTTP/1.0 502 Bad Gateway\r\n";
|
||||
const std::string service_unavailable =
|
||||
"HTTP/1.0 503 Service Unavailable\r\n";
|
||||
|
||||
asio::const_buffer to_buffer(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return asio::buffer(ok);
|
||||
case reply::created:
|
||||
return asio::buffer(created);
|
||||
case reply::accepted:
|
||||
return asio::buffer(accepted);
|
||||
case reply::no_content:
|
||||
return asio::buffer(no_content);
|
||||
case reply::multiple_choices:
|
||||
return asio::buffer(multiple_choices);
|
||||
case reply::moved_permanently:
|
||||
return asio::buffer(moved_permanently);
|
||||
case reply::moved_temporarily:
|
||||
return asio::buffer(moved_temporarily);
|
||||
case reply::not_modified:
|
||||
return asio::buffer(not_modified);
|
||||
case reply::bad_request:
|
||||
return asio::buffer(bad_request);
|
||||
case reply::unauthorized:
|
||||
return asio::buffer(unauthorized);
|
||||
case reply::forbidden:
|
||||
return asio::buffer(forbidden);
|
||||
case reply::not_found:
|
||||
return asio::buffer(not_found);
|
||||
case reply::internal_server_error:
|
||||
return asio::buffer(internal_server_error);
|
||||
case reply::not_implemented:
|
||||
return asio::buffer(not_implemented);
|
||||
case reply::bad_gateway:
|
||||
return asio::buffer(bad_gateway);
|
||||
case reply::service_unavailable:
|
||||
return asio::buffer(service_unavailable);
|
||||
default:
|
||||
return asio::buffer(internal_server_error);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace status_strings
|
||||
|
||||
namespace misc_strings {
|
||||
|
||||
const char name_value_separator[] = { ':', ' ' };
|
||||
const char crlf[] = { '\r', '\n' };
|
||||
|
||||
} // namespace misc_strings
|
||||
|
||||
std::vector<asio::const_buffer> reply::to_buffers()
|
||||
{
|
||||
std::vector<asio::const_buffer> buffers;
|
||||
buffers.push_back(status_strings::to_buffer(status));
|
||||
for (std::size_t i = 0; i < headers.size(); ++i)
|
||||
{
|
||||
header& h = headers[i];
|
||||
buffers.push_back(asio::buffer(h.name));
|
||||
buffers.push_back(asio::buffer(misc_strings::name_value_separator));
|
||||
buffers.push_back(asio::buffer(h.value));
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
}
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
buffers.push_back(asio::buffer(content));
|
||||
return buffers;
|
||||
}
|
||||
|
||||
namespace stock_replies {
|
||||
|
||||
const char ok[] = "";
|
||||
const char created[] =
|
||||
"<html>"
|
||||
"<head><title>Created</title></head>"
|
||||
"<body><h1>201 Created</h1></body>"
|
||||
"</html>";
|
||||
const char accepted[] =
|
||||
"<html>"
|
||||
"<head><title>Accepted</title></head>"
|
||||
"<body><h1>202 Accepted</h1></body>"
|
||||
"</html>";
|
||||
const char no_content[] =
|
||||
"<html>"
|
||||
"<head><title>No Content</title></head>"
|
||||
"<body><h1>204 Content</h1></body>"
|
||||
"</html>";
|
||||
const char multiple_choices[] =
|
||||
"<html>"
|
||||
"<head><title>Multiple Choices</title></head>"
|
||||
"<body><h1>300 Multiple Choices</h1></body>"
|
||||
"</html>";
|
||||
const char moved_permanently[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Permanently</title></head>"
|
||||
"<body><h1>301 Moved Permanently</h1></body>"
|
||||
"</html>";
|
||||
const char moved_temporarily[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Temporarily</title></head>"
|
||||
"<body><h1>302 Moved Temporarily</h1></body>"
|
||||
"</html>";
|
||||
const char not_modified[] =
|
||||
"<html>"
|
||||
"<head><title>Not Modified</title></head>"
|
||||
"<body><h1>304 Not Modified</h1></body>"
|
||||
"</html>";
|
||||
const char bad_request[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Request</title></head>"
|
||||
"<body><h1>400 Bad Request</h1></body>"
|
||||
"</html>";
|
||||
const char unauthorized[] =
|
||||
"<html>"
|
||||
"<head><title>Unauthorized</title></head>"
|
||||
"<body><h1>401 Unauthorized</h1></body>"
|
||||
"</html>";
|
||||
const char forbidden[] =
|
||||
"<html>"
|
||||
"<head><title>Forbidden</title></head>"
|
||||
"<body><h1>403 Forbidden</h1></body>"
|
||||
"</html>";
|
||||
const char not_found[] =
|
||||
"<html>"
|
||||
"<head><title>Not Found</title></head>"
|
||||
"<body><h1>404 Not Found</h1></body>"
|
||||
"</html>";
|
||||
const char internal_server_error[] =
|
||||
"<html>"
|
||||
"<head><title>Internal Server Error</title></head>"
|
||||
"<body><h1>500 Internal Server Error</h1></body>"
|
||||
"</html>";
|
||||
const char not_implemented[] =
|
||||
"<html>"
|
||||
"<head><title>Not Implemented</title></head>"
|
||||
"<body><h1>501 Not Implemented</h1></body>"
|
||||
"</html>";
|
||||
const char bad_gateway[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Gateway</title></head>"
|
||||
"<body><h1>502 Bad Gateway</h1></body>"
|
||||
"</html>";
|
||||
const char service_unavailable[] =
|
||||
"<html>"
|
||||
"<head><title>Service Unavailable</title></head>"
|
||||
"<body><h1>503 Service Unavailable</h1></body>"
|
||||
"</html>";
|
||||
|
||||
std::string to_string(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return ok;
|
||||
case reply::created:
|
||||
return created;
|
||||
case reply::accepted:
|
||||
return accepted;
|
||||
case reply::no_content:
|
||||
return no_content;
|
||||
case reply::multiple_choices:
|
||||
return multiple_choices;
|
||||
case reply::moved_permanently:
|
||||
return moved_permanently;
|
||||
case reply::moved_temporarily:
|
||||
return moved_temporarily;
|
||||
case reply::not_modified:
|
||||
return not_modified;
|
||||
case reply::bad_request:
|
||||
return bad_request;
|
||||
case reply::unauthorized:
|
||||
return unauthorized;
|
||||
case reply::forbidden:
|
||||
return forbidden;
|
||||
case reply::not_found:
|
||||
return not_found;
|
||||
case reply::internal_server_error:
|
||||
return internal_server_error;
|
||||
case reply::not_implemented:
|
||||
return not_implemented;
|
||||
case reply::bad_gateway:
|
||||
return bad_gateway;
|
||||
case reply::service_unavailable:
|
||||
return service_unavailable;
|
||||
default:
|
||||
return internal_server_error;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace stock_replies
|
||||
|
||||
reply reply::stock_reply(reply::status_type status)
|
||||
{
|
||||
reply rep;
|
||||
rep.status = status;
|
||||
rep.content = stock_replies::to_string(status);
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = "text/html";
|
||||
return rep;
|
||||
}
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
64
asio/src/examples/cpp03/http/server2/reply.hpp
Normal file
64
asio/src/examples/cpp03/http/server2/reply.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// reply.hpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_REPLY_HPP
|
||||
#define HTTP_SERVER2_REPLY_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <asio.hpp>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
/// A reply to be sent to a client.
|
||||
struct reply
|
||||
{
|
||||
/// The status of the reply.
|
||||
enum status_type
|
||||
{
|
||||
ok = 200,
|
||||
created = 201,
|
||||
accepted = 202,
|
||||
no_content = 204,
|
||||
multiple_choices = 300,
|
||||
moved_permanently = 301,
|
||||
moved_temporarily = 302,
|
||||
not_modified = 304,
|
||||
bad_request = 400,
|
||||
unauthorized = 401,
|
||||
forbidden = 403,
|
||||
not_found = 404,
|
||||
internal_server_error = 500,
|
||||
not_implemented = 501,
|
||||
bad_gateway = 502,
|
||||
service_unavailable = 503
|
||||
} status;
|
||||
|
||||
/// The headers to be included in the reply.
|
||||
std::vector<header> headers;
|
||||
|
||||
/// The content to be sent in the reply.
|
||||
std::string content;
|
||||
|
||||
/// Convert the reply into a vector of buffers. The buffers do not own the
|
||||
/// underlying memory blocks, therefore the reply object must remain valid and
|
||||
/// not be changed until the write operation has completed.
|
||||
std::vector<asio::const_buffer> to_buffers();
|
||||
|
||||
/// Get a stock reply.
|
||||
static reply stock_reply(status_type status);
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_REPLY_HPP
|
||||
34
asio/src/examples/cpp03/http/server2/request.hpp
Normal file
34
asio/src/examples/cpp03/http/server2/request.hpp
Normal file
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// request.hpp
|
||||
// ~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_REQUEST_HPP
|
||||
#define HTTP_SERVER2_REQUEST_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
/// A request received from a client.
|
||||
struct request
|
||||
{
|
||||
std::string method;
|
||||
std::string uri;
|
||||
int http_version_major;
|
||||
int http_version_minor;
|
||||
std::vector<header> headers;
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_REQUEST_HPP
|
||||
122
asio/src/examples/cpp03/http/server2/request_handler.cpp
Normal file
122
asio/src/examples/cpp03/http/server2/request_handler.cpp
Normal file
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// request_handler.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_handler.hpp"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "mime_types.hpp"
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
request_handler::request_handler(const std::string& doc_root)
|
||||
: doc_root_(doc_root)
|
||||
{
|
||||
}
|
||||
|
||||
void request_handler::handle_request(const request& req, reply& rep)
|
||||
{
|
||||
// Decode url to path.
|
||||
std::string request_path;
|
||||
if (!url_decode(req.uri, request_path))
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// Request path must be absolute and not contain "..".
|
||||
if (request_path.empty() || request_path[0] != '/'
|
||||
|| request_path.find("..") != std::string::npos)
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// If path ends in slash (i.e. is a directory) then add "index.html".
|
||||
if (request_path[request_path.size() - 1] == '/')
|
||||
{
|
||||
request_path += "index.html";
|
||||
}
|
||||
|
||||
// Determine the file extension.
|
||||
std::size_t last_slash_pos = request_path.find_last_of("/");
|
||||
std::size_t last_dot_pos = request_path.find_last_of(".");
|
||||
std::string extension;
|
||||
if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos)
|
||||
{
|
||||
extension = request_path.substr(last_dot_pos + 1);
|
||||
}
|
||||
|
||||
// Open the file to send back.
|
||||
std::string full_path = doc_root_ + request_path;
|
||||
std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
|
||||
if (!is)
|
||||
{
|
||||
rep = reply::stock_reply(reply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill out the reply to be sent to the client.
|
||||
rep.status = reply::ok;
|
||||
char buf[512];
|
||||
while (is.read(buf, sizeof(buf)).gcount() > 0)
|
||||
rep.content.append(buf, is.gcount());
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = mime_types::extension_to_type(extension);
|
||||
}
|
||||
|
||||
bool request_handler::url_decode(const std::string& in, std::string& out)
|
||||
{
|
||||
out.clear();
|
||||
out.reserve(in.size());
|
||||
for (std::size_t i = 0; i < in.size(); ++i)
|
||||
{
|
||||
if (in[i] == '%')
|
||||
{
|
||||
if (i + 3 <= in.size())
|
||||
{
|
||||
int value = 0;
|
||||
std::istringstream is(in.substr(i + 1, 2));
|
||||
if (is >> std::hex >> value)
|
||||
{
|
||||
out += static_cast<char>(value);
|
||||
i += 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (in[i] == '+')
|
||||
{
|
||||
out += ' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
out += in[i];
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
46
asio/src/examples/cpp03/http/server2/request_handler.hpp
Normal file
46
asio/src/examples/cpp03/http/server2/request_handler.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// request_handler.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_REQUEST_HANDLER_HPP
|
||||
#define HTTP_SERVER2_REQUEST_HANDLER_HPP
|
||||
|
||||
#include <string>
|
||||
#include <boost/noncopyable.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
struct reply;
|
||||
struct request;
|
||||
|
||||
/// The common handler for all incoming requests.
|
||||
class request_handler
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct with a directory containing files to be served.
|
||||
explicit request_handler(const std::string& doc_root);
|
||||
|
||||
/// Handle a request and produce a reply.
|
||||
void handle_request(const request& req, reply& rep);
|
||||
|
||||
private:
|
||||
/// The directory containing the files to be served.
|
||||
std::string doc_root_;
|
||||
|
||||
/// Perform URL-decoding on a string. Returns false if the encoding was
|
||||
/// invalid.
|
||||
static bool url_decode(const std::string& in, std::string& out);
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_REQUEST_HANDLER_HPP
|
||||
315
asio/src/examples/cpp03/http/server2/request_parser.cpp
Normal file
315
asio/src/examples/cpp03/http/server2/request_parser.cpp
Normal file
@@ -0,0 +1,315 @@
|
||||
//
|
||||
// request_parser.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_parser.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
request_parser::request_parser()
|
||||
: state_(method_start)
|
||||
{
|
||||
}
|
||||
|
||||
void request_parser::reset()
|
||||
{
|
||||
state_ = method_start;
|
||||
}
|
||||
|
||||
boost::tribool request_parser::consume(request& req, char input)
|
||||
{
|
||||
switch (state_)
|
||||
{
|
||||
case method_start:
|
||||
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = method;
|
||||
req.method.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case method:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = uri;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.method.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case uri:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = http_version_h;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.uri.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case http_version_h:
|
||||
if (input == 'H')
|
||||
{
|
||||
state_ = http_version_t_1;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_t_1:
|
||||
if (input == 'T')
|
||||
{
|
||||
state_ = http_version_t_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_t_2:
|
||||
if (input == 'T')
|
||||
{
|
||||
state_ = http_version_p;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_p:
|
||||
if (input == 'P')
|
||||
{
|
||||
state_ = http_version_slash;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_slash:
|
||||
if (input == '/')
|
||||
{
|
||||
req.http_version_major = 0;
|
||||
req.http_version_minor = 0;
|
||||
state_ = http_version_major_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_major_start:
|
||||
if (is_digit(input))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + input - '0';
|
||||
state_ = http_version_major;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_major:
|
||||
if (input == '.')
|
||||
{
|
||||
state_ = http_version_minor_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_digit(input))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + input - '0';
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_minor_start:
|
||||
if (is_digit(input))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + input - '0';
|
||||
state_ = http_version_minor;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_minor:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_1;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_digit(input))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + input - '0';
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case expecting_newline_1:
|
||||
if (input == '\n')
|
||||
{
|
||||
state_ = header_line_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case header_line_start:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_3;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!req.headers.empty() && (input == ' ' || input == '\t'))
|
||||
{
|
||||
state_ = header_lws;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.push_back(header());
|
||||
req.headers.back().name.push_back(input);
|
||||
state_ = header_name;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case header_lws:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (input == ' ' || input == '\t')
|
||||
{
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = header_value;
|
||||
req.headers.back().value.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case header_name:
|
||||
if (input == ':')
|
||||
{
|
||||
state_ = space_before_header_value;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.back().name.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case space_before_header_value:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = header_value;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case header_value:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.back().value.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case expecting_newline_2:
|
||||
if (input == '\n')
|
||||
{
|
||||
state_ = header_line_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case expecting_newline_3:
|
||||
return (input == '\n');
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_char(int c)
|
||||
{
|
||||
return c >= 0 && c <= 127;
|
||||
}
|
||||
|
||||
bool request_parser::is_ctl(int c)
|
||||
{
|
||||
return (c >= 0 && c <= 31) || (c == 127);
|
||||
}
|
||||
|
||||
bool request_parser::is_tspecial(int c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '(': case ')': case '<': case '>': case '@':
|
||||
case ',': case ';': case ':': case '\\': case '"':
|
||||
case '/': case '[': case ']': case '?': case '=':
|
||||
case '{': case '}': case ' ': case '\t':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_digit(int c)
|
||||
{
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
95
asio/src/examples/cpp03/http/server2/request_parser.hpp
Normal file
95
asio/src/examples/cpp03/http/server2/request_parser.hpp
Normal file
@@ -0,0 +1,95 @@
|
||||
//
|
||||
// request_parser.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_REQUEST_PARSER_HPP
|
||||
#define HTTP_SERVER2_REQUEST_PARSER_HPP
|
||||
|
||||
#include <boost/logic/tribool.hpp>
|
||||
#include <boost/tuple/tuple.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
struct request;
|
||||
|
||||
/// Parser for incoming requests.
|
||||
class request_parser
|
||||
{
|
||||
public:
|
||||
/// Construct ready to parse the request method.
|
||||
request_parser();
|
||||
|
||||
/// Reset to initial parser state.
|
||||
void reset();
|
||||
|
||||
/// Parse some data. The tribool return value is true when a complete request
|
||||
/// has been parsed, false if the data is invalid, indeterminate when more
|
||||
/// data is required. The InputIterator return value indicates how much of the
|
||||
/// input has been consumed.
|
||||
template <typename InputIterator>
|
||||
boost::tuple<boost::tribool, InputIterator> parse(request& req,
|
||||
InputIterator begin, InputIterator end)
|
||||
{
|
||||
while (begin != end)
|
||||
{
|
||||
boost::tribool result = consume(req, *begin++);
|
||||
if (result || !result)
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
boost::tribool result = boost::indeterminate;
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
|
||||
private:
|
||||
/// Handle the next character of input.
|
||||
boost::tribool consume(request& req, char input);
|
||||
|
||||
/// Check if a byte is an HTTP character.
|
||||
static bool is_char(int c);
|
||||
|
||||
/// Check if a byte is an HTTP control character.
|
||||
static bool is_ctl(int c);
|
||||
|
||||
/// Check if a byte is defined as an HTTP tspecial character.
|
||||
static bool is_tspecial(int c);
|
||||
|
||||
/// Check if a byte is a digit.
|
||||
static bool is_digit(int c);
|
||||
|
||||
/// The current state of the parser.
|
||||
enum state
|
||||
{
|
||||
method_start,
|
||||
method,
|
||||
uri,
|
||||
http_version_h,
|
||||
http_version_t_1,
|
||||
http_version_t_2,
|
||||
http_version_p,
|
||||
http_version_slash,
|
||||
http_version_major_start,
|
||||
http_version_major,
|
||||
http_version_minor_start,
|
||||
http_version_minor,
|
||||
expecting_newline_1,
|
||||
header_line_start,
|
||||
header_lws,
|
||||
header_name,
|
||||
space_before_header_value,
|
||||
header_value,
|
||||
expecting_newline_2,
|
||||
expecting_newline_3
|
||||
} state_;
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_REQUEST_PARSER_HPP
|
||||
77
asio/src/examples/cpp03/http/server2/server.cpp
Normal file
77
asio/src/examples/cpp03/http/server2/server.cpp
Normal file
@@ -0,0 +1,77 @@
|
||||
//
|
||||
// server.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "server.hpp"
|
||||
#include <boost/bind/bind.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
server::server(const std::string& address, const std::string& port,
|
||||
const std::string& doc_root, std::size_t io_context_pool_size)
|
||||
: io_context_pool_(io_context_pool_size),
|
||||
signals_(io_context_pool_.get_io_context()),
|
||||
acceptor_(io_context_pool_.get_io_context()),
|
||||
new_connection_(),
|
||||
request_handler_(doc_root)
|
||||
{
|
||||
// Register to handle the signals that indicate when the server should exit.
|
||||
// It is safe to register for the same signal multiple times in a program,
|
||||
// provided all registration for the specified signal is made through Asio.
|
||||
signals_.add(SIGINT);
|
||||
signals_.add(SIGTERM);
|
||||
#if defined(SIGQUIT)
|
||||
signals_.add(SIGQUIT);
|
||||
#endif // defined(SIGQUIT)
|
||||
signals_.async_wait(boost::bind(&server::handle_stop, this));
|
||||
|
||||
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
|
||||
asio::ip::tcp::resolver resolver(acceptor_.get_executor());
|
||||
asio::ip::tcp::endpoint endpoint =
|
||||
*resolver.resolve(address, port).begin();
|
||||
acceptor_.open(endpoint.protocol());
|
||||
acceptor_.set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
||||
acceptor_.bind(endpoint);
|
||||
acceptor_.listen();
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void server::run()
|
||||
{
|
||||
io_context_pool_.run();
|
||||
}
|
||||
|
||||
void server::start_accept()
|
||||
{
|
||||
new_connection_.reset(new connection(
|
||||
io_context_pool_.get_io_context(), request_handler_));
|
||||
acceptor_.async_accept(new_connection_->socket(),
|
||||
boost::bind(&server::handle_accept, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void server::handle_accept(const asio::error_code& e)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
new_connection_->start();
|
||||
}
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void server::handle_stop()
|
||||
{
|
||||
io_context_pool_.stop();
|
||||
}
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
68
asio/src/examples/cpp03/http/server2/server.hpp
Normal file
68
asio/src/examples/cpp03/http/server2/server.hpp
Normal file
@@ -0,0 +1,68 @@
|
||||
//
|
||||
// server.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER2_SERVER_HPP
|
||||
#define HTTP_SERVER2_SERVER_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include "connection.hpp"
|
||||
#include "io_context_pool.hpp"
|
||||
#include "request_handler.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server2 {
|
||||
|
||||
/// The top-level class of the HTTP server.
|
||||
class server
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct the server to listen on the specified TCP address and port, and
|
||||
/// serve up files from the given directory.
|
||||
explicit server(const std::string& address, const std::string& port,
|
||||
const std::string& doc_root, std::size_t io_context_pool_size);
|
||||
|
||||
/// Run the server's io_context loop.
|
||||
void run();
|
||||
|
||||
private:
|
||||
/// Initiate an asynchronous accept operation.
|
||||
void start_accept();
|
||||
|
||||
/// Handle completion of an asynchronous accept operation.
|
||||
void handle_accept(const asio::error_code& e);
|
||||
|
||||
/// Handle a request to stop the server.
|
||||
void handle_stop();
|
||||
|
||||
/// The pool of io_context objects used to perform asynchronous operations.
|
||||
io_context_pool io_context_pool_;
|
||||
|
||||
/// The signal_set is used to register for process termination notifications.
|
||||
asio::signal_set signals_;
|
||||
|
||||
/// Acceptor used to listen for incoming connections.
|
||||
asio::ip::tcp::acceptor acceptor_;
|
||||
|
||||
/// The next connection to be accepted.
|
||||
connection_ptr new_connection_;
|
||||
|
||||
/// The handler for all incoming requests.
|
||||
request_handler request_handler_;
|
||||
};
|
||||
|
||||
} // namespace server2
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER2_SERVER_HPP
|
||||
94
asio/src/examples/cpp03/http/server3/connection.cpp
Normal file
94
asio/src/examples/cpp03/http/server3/connection.cpp
Normal file
@@ -0,0 +1,94 @@
|
||||
//
|
||||
// connection.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "connection.hpp"
|
||||
#include <vector>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include "request_handler.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
connection::connection(asio::io_context& io_context,
|
||||
request_handler& handler)
|
||||
: strand_(asio::make_strand(io_context)),
|
||||
socket_(strand_),
|
||||
request_handler_(handler)
|
||||
{
|
||||
}
|
||||
|
||||
asio::ip::tcp::socket& connection::socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void connection::start()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(buffer_),
|
||||
boost::bind(&connection::handle_read, shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void connection::handle_read(const asio::error_code& e,
|
||||
std::size_t bytes_transferred)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
boost::tribool result;
|
||||
boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
|
||||
request_, buffer_.data(), buffer_.data() + bytes_transferred);
|
||||
|
||||
if (result)
|
||||
{
|
||||
request_handler_.handle_request(request_, reply_);
|
||||
asio::async_write(socket_, reply_.to_buffers(),
|
||||
boost::bind(&connection::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else if (!result)
|
||||
{
|
||||
reply_ = reply::stock_reply(reply::bad_request);
|
||||
asio::async_write(socket_, reply_.to_buffers(),
|
||||
boost::bind(&connection::handle_write, shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(buffer_),
|
||||
boost::bind(&connection::handle_read, shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
|
||||
// If an error occurs then no new asynchronous operations are started. This
|
||||
// means that all shared_ptr references to the connection object will
|
||||
// disappear and the object will be destroyed automatically after this
|
||||
// handler returns. The connection class's destructor closes the socket.
|
||||
}
|
||||
|
||||
void connection::handle_write(const asio::error_code& e)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
// Initiate graceful connection closure.
|
||||
asio::error_code ignored_ec;
|
||||
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec);
|
||||
}
|
||||
|
||||
// No new asynchronous operations are started. This means that all shared_ptr
|
||||
// references to the connection object will disappear and the object will be
|
||||
// destroyed automatically after this handler returns. The connection class's
|
||||
// destructor closes the socket.
|
||||
}
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
78
asio/src/examples/cpp03/http/server3/connection.hpp
Normal file
78
asio/src/examples/cpp03/http/server3/connection.hpp
Normal file
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// connection.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_CONNECTION_HPP
|
||||
#define HTTP_SERVER3_CONNECTION_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
#include "request_handler.hpp"
|
||||
#include "request_parser.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
/// Represents a single connection from a client.
|
||||
class connection
|
||||
: public boost::enable_shared_from_this<connection>,
|
||||
private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct a connection with the given io_context.
|
||||
explicit connection(asio::io_context& io_context,
|
||||
request_handler& handler);
|
||||
|
||||
/// Get the socket associated with the connection.
|
||||
asio::ip::tcp::socket& socket();
|
||||
|
||||
/// Start the first asynchronous operation for the connection.
|
||||
void start();
|
||||
|
||||
private:
|
||||
/// Handle completion of a read operation.
|
||||
void handle_read(const asio::error_code& e,
|
||||
std::size_t bytes_transferred);
|
||||
|
||||
/// Handle completion of a write operation.
|
||||
void handle_write(const asio::error_code& e);
|
||||
|
||||
/// Strand to ensure the connection's handlers are not called concurrently.
|
||||
asio::strand<asio::io_context::executor_type> strand_;
|
||||
|
||||
/// Socket for the connection.
|
||||
asio::ip::tcp::socket socket_;
|
||||
|
||||
/// The handler used to process the incoming request.
|
||||
request_handler& request_handler_;
|
||||
|
||||
/// Buffer for incoming data.
|
||||
boost::array<char, 8192> buffer_;
|
||||
|
||||
/// The incoming request.
|
||||
request request_;
|
||||
|
||||
/// The parser for the incoming request.
|
||||
request_parser request_parser_;
|
||||
|
||||
/// The reply to be sent back to the client.
|
||||
reply reply_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<connection> connection_ptr;
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_CONNECTION_HPP
|
||||
28
asio/src/examples/cpp03/http/server3/header.hpp
Normal file
28
asio/src/examples/cpp03/http/server3/header.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// header.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_HEADER_HPP
|
||||
#define HTTP_SERVER3_HEADER_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
struct header
|
||||
{
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_HEADER_HPP
|
||||
46
asio/src/examples/cpp03/http/server3/main.cpp
Normal file
46
asio/src/examples/cpp03/http/server3/main.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// main.cpp
|
||||
// ~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "server.hpp"
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check command line arguments.
|
||||
if (argc != 5)
|
||||
{
|
||||
std::cerr << "Usage: http_server <address> <port> <threads> <doc_root>\n";
|
||||
std::cerr << " For IPv4, try:\n";
|
||||
std::cerr << " receiver 0.0.0.0 80 1 .\n";
|
||||
std::cerr << " For IPv6, try:\n";
|
||||
std::cerr << " receiver 0::0 80 1 .\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Initialise the server.
|
||||
std::size_t num_threads = boost::lexical_cast<std::size_t>(argv[3]);
|
||||
http::server3::server s(argv[1], argv[2], argv[4], num_threads);
|
||||
|
||||
// Run the server until stopped.
|
||||
s.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
46
asio/src/examples/cpp03/http/server3/mime_types.cpp
Normal file
46
asio/src/examples/cpp03/http/server3/mime_types.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// mime_types.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "mime_types.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
namespace mime_types {
|
||||
|
||||
struct mapping
|
||||
{
|
||||
const char* extension;
|
||||
const char* mime_type;
|
||||
} mappings[] =
|
||||
{
|
||||
{ "gif", "image/gif" },
|
||||
{ "htm", "text/html" },
|
||||
{ "html", "text/html" },
|
||||
{ "jpg", "image/jpeg" },
|
||||
{ "png", "image/png" },
|
||||
{ 0, 0 } // Marks end of list.
|
||||
};
|
||||
|
||||
std::string extension_to_type(const std::string& extension)
|
||||
{
|
||||
for (mapping* m = mappings; m->extension; ++m)
|
||||
{
|
||||
if (m->extension == extension)
|
||||
{
|
||||
return m->mime_type;
|
||||
}
|
||||
}
|
||||
|
||||
return "text/plain";
|
||||
}
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
27
asio/src/examples/cpp03/http/server3/mime_types.hpp
Normal file
27
asio/src/examples/cpp03/http/server3/mime_types.hpp
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// mime_types.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_MIME_TYPES_HPP
|
||||
#define HTTP_SERVER3_MIME_TYPES_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
namespace mime_types {
|
||||
|
||||
/// Convert a file extension into a MIME type.
|
||||
std::string extension_to_type(const std::string& extension);
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_MIME_TYPES_HPP
|
||||
256
asio/src/examples/cpp03/http/server3/reply.cpp
Normal file
256
asio/src/examples/cpp03/http/server3/reply.cpp
Normal file
@@ -0,0 +1,256 @@
|
||||
//
|
||||
// reply.cpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "reply.hpp"
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
namespace status_strings {
|
||||
|
||||
const std::string ok =
|
||||
"HTTP/1.0 200 OK\r\n";
|
||||
const std::string created =
|
||||
"HTTP/1.0 201 Created\r\n";
|
||||
const std::string accepted =
|
||||
"HTTP/1.0 202 Accepted\r\n";
|
||||
const std::string no_content =
|
||||
"HTTP/1.0 204 No Content\r\n";
|
||||
const std::string multiple_choices =
|
||||
"HTTP/1.0 300 Multiple Choices\r\n";
|
||||
const std::string moved_permanently =
|
||||
"HTTP/1.0 301 Moved Permanently\r\n";
|
||||
const std::string moved_temporarily =
|
||||
"HTTP/1.0 302 Moved Temporarily\r\n";
|
||||
const std::string not_modified =
|
||||
"HTTP/1.0 304 Not Modified\r\n";
|
||||
const std::string bad_request =
|
||||
"HTTP/1.0 400 Bad Request\r\n";
|
||||
const std::string unauthorized =
|
||||
"HTTP/1.0 401 Unauthorized\r\n";
|
||||
const std::string forbidden =
|
||||
"HTTP/1.0 403 Forbidden\r\n";
|
||||
const std::string not_found =
|
||||
"HTTP/1.0 404 Not Found\r\n";
|
||||
const std::string internal_server_error =
|
||||
"HTTP/1.0 500 Internal Server Error\r\n";
|
||||
const std::string not_implemented =
|
||||
"HTTP/1.0 501 Not Implemented\r\n";
|
||||
const std::string bad_gateway =
|
||||
"HTTP/1.0 502 Bad Gateway\r\n";
|
||||
const std::string service_unavailable =
|
||||
"HTTP/1.0 503 Service Unavailable\r\n";
|
||||
|
||||
asio::const_buffer to_buffer(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return asio::buffer(ok);
|
||||
case reply::created:
|
||||
return asio::buffer(created);
|
||||
case reply::accepted:
|
||||
return asio::buffer(accepted);
|
||||
case reply::no_content:
|
||||
return asio::buffer(no_content);
|
||||
case reply::multiple_choices:
|
||||
return asio::buffer(multiple_choices);
|
||||
case reply::moved_permanently:
|
||||
return asio::buffer(moved_permanently);
|
||||
case reply::moved_temporarily:
|
||||
return asio::buffer(moved_temporarily);
|
||||
case reply::not_modified:
|
||||
return asio::buffer(not_modified);
|
||||
case reply::bad_request:
|
||||
return asio::buffer(bad_request);
|
||||
case reply::unauthorized:
|
||||
return asio::buffer(unauthorized);
|
||||
case reply::forbidden:
|
||||
return asio::buffer(forbidden);
|
||||
case reply::not_found:
|
||||
return asio::buffer(not_found);
|
||||
case reply::internal_server_error:
|
||||
return asio::buffer(internal_server_error);
|
||||
case reply::not_implemented:
|
||||
return asio::buffer(not_implemented);
|
||||
case reply::bad_gateway:
|
||||
return asio::buffer(bad_gateway);
|
||||
case reply::service_unavailable:
|
||||
return asio::buffer(service_unavailable);
|
||||
default:
|
||||
return asio::buffer(internal_server_error);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace status_strings
|
||||
|
||||
namespace misc_strings {
|
||||
|
||||
const char name_value_separator[] = { ':', ' ' };
|
||||
const char crlf[] = { '\r', '\n' };
|
||||
|
||||
} // namespace misc_strings
|
||||
|
||||
std::vector<asio::const_buffer> reply::to_buffers()
|
||||
{
|
||||
std::vector<asio::const_buffer> buffers;
|
||||
buffers.push_back(status_strings::to_buffer(status));
|
||||
for (std::size_t i = 0; i < headers.size(); ++i)
|
||||
{
|
||||
header& h = headers[i];
|
||||
buffers.push_back(asio::buffer(h.name));
|
||||
buffers.push_back(asio::buffer(misc_strings::name_value_separator));
|
||||
buffers.push_back(asio::buffer(h.value));
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
}
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
buffers.push_back(asio::buffer(content));
|
||||
return buffers;
|
||||
}
|
||||
|
||||
namespace stock_replies {
|
||||
|
||||
const char ok[] = "";
|
||||
const char created[] =
|
||||
"<html>"
|
||||
"<head><title>Created</title></head>"
|
||||
"<body><h1>201 Created</h1></body>"
|
||||
"</html>";
|
||||
const char accepted[] =
|
||||
"<html>"
|
||||
"<head><title>Accepted</title></head>"
|
||||
"<body><h1>202 Accepted</h1></body>"
|
||||
"</html>";
|
||||
const char no_content[] =
|
||||
"<html>"
|
||||
"<head><title>No Content</title></head>"
|
||||
"<body><h1>204 Content</h1></body>"
|
||||
"</html>";
|
||||
const char multiple_choices[] =
|
||||
"<html>"
|
||||
"<head><title>Multiple Choices</title></head>"
|
||||
"<body><h1>300 Multiple Choices</h1></body>"
|
||||
"</html>";
|
||||
const char moved_permanently[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Permanently</title></head>"
|
||||
"<body><h1>301 Moved Permanently</h1></body>"
|
||||
"</html>";
|
||||
const char moved_temporarily[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Temporarily</title></head>"
|
||||
"<body><h1>302 Moved Temporarily</h1></body>"
|
||||
"</html>";
|
||||
const char not_modified[] =
|
||||
"<html>"
|
||||
"<head><title>Not Modified</title></head>"
|
||||
"<body><h1>304 Not Modified</h1></body>"
|
||||
"</html>";
|
||||
const char bad_request[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Request</title></head>"
|
||||
"<body><h1>400 Bad Request</h1></body>"
|
||||
"</html>";
|
||||
const char unauthorized[] =
|
||||
"<html>"
|
||||
"<head><title>Unauthorized</title></head>"
|
||||
"<body><h1>401 Unauthorized</h1></body>"
|
||||
"</html>";
|
||||
const char forbidden[] =
|
||||
"<html>"
|
||||
"<head><title>Forbidden</title></head>"
|
||||
"<body><h1>403 Forbidden</h1></body>"
|
||||
"</html>";
|
||||
const char not_found[] =
|
||||
"<html>"
|
||||
"<head><title>Not Found</title></head>"
|
||||
"<body><h1>404 Not Found</h1></body>"
|
||||
"</html>";
|
||||
const char internal_server_error[] =
|
||||
"<html>"
|
||||
"<head><title>Internal Server Error</title></head>"
|
||||
"<body><h1>500 Internal Server Error</h1></body>"
|
||||
"</html>";
|
||||
const char not_implemented[] =
|
||||
"<html>"
|
||||
"<head><title>Not Implemented</title></head>"
|
||||
"<body><h1>501 Not Implemented</h1></body>"
|
||||
"</html>";
|
||||
const char bad_gateway[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Gateway</title></head>"
|
||||
"<body><h1>502 Bad Gateway</h1></body>"
|
||||
"</html>";
|
||||
const char service_unavailable[] =
|
||||
"<html>"
|
||||
"<head><title>Service Unavailable</title></head>"
|
||||
"<body><h1>503 Service Unavailable</h1></body>"
|
||||
"</html>";
|
||||
|
||||
std::string to_string(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return ok;
|
||||
case reply::created:
|
||||
return created;
|
||||
case reply::accepted:
|
||||
return accepted;
|
||||
case reply::no_content:
|
||||
return no_content;
|
||||
case reply::multiple_choices:
|
||||
return multiple_choices;
|
||||
case reply::moved_permanently:
|
||||
return moved_permanently;
|
||||
case reply::moved_temporarily:
|
||||
return moved_temporarily;
|
||||
case reply::not_modified:
|
||||
return not_modified;
|
||||
case reply::bad_request:
|
||||
return bad_request;
|
||||
case reply::unauthorized:
|
||||
return unauthorized;
|
||||
case reply::forbidden:
|
||||
return forbidden;
|
||||
case reply::not_found:
|
||||
return not_found;
|
||||
case reply::internal_server_error:
|
||||
return internal_server_error;
|
||||
case reply::not_implemented:
|
||||
return not_implemented;
|
||||
case reply::bad_gateway:
|
||||
return bad_gateway;
|
||||
case reply::service_unavailable:
|
||||
return service_unavailable;
|
||||
default:
|
||||
return internal_server_error;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace stock_replies
|
||||
|
||||
reply reply::stock_reply(reply::status_type status)
|
||||
{
|
||||
reply rep;
|
||||
rep.status = status;
|
||||
rep.content = stock_replies::to_string(status);
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = "text/html";
|
||||
return rep;
|
||||
}
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
64
asio/src/examples/cpp03/http/server3/reply.hpp
Normal file
64
asio/src/examples/cpp03/http/server3/reply.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// reply.hpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_REPLY_HPP
|
||||
#define HTTP_SERVER3_REPLY_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <asio.hpp>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
/// A reply to be sent to a client.
|
||||
struct reply
|
||||
{
|
||||
/// The status of the reply.
|
||||
enum status_type
|
||||
{
|
||||
ok = 200,
|
||||
created = 201,
|
||||
accepted = 202,
|
||||
no_content = 204,
|
||||
multiple_choices = 300,
|
||||
moved_permanently = 301,
|
||||
moved_temporarily = 302,
|
||||
not_modified = 304,
|
||||
bad_request = 400,
|
||||
unauthorized = 401,
|
||||
forbidden = 403,
|
||||
not_found = 404,
|
||||
internal_server_error = 500,
|
||||
not_implemented = 501,
|
||||
bad_gateway = 502,
|
||||
service_unavailable = 503
|
||||
} status;
|
||||
|
||||
/// The headers to be included in the reply.
|
||||
std::vector<header> headers;
|
||||
|
||||
/// The content to be sent in the reply.
|
||||
std::string content;
|
||||
|
||||
/// Convert the reply into a vector of buffers. The buffers do not own the
|
||||
/// underlying memory blocks, therefore the reply object must remain valid and
|
||||
/// not be changed until the write operation has completed.
|
||||
std::vector<asio::const_buffer> to_buffers();
|
||||
|
||||
/// Get a stock reply.
|
||||
static reply stock_reply(status_type status);
|
||||
};
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_REPLY_HPP
|
||||
34
asio/src/examples/cpp03/http/server3/request.hpp
Normal file
34
asio/src/examples/cpp03/http/server3/request.hpp
Normal file
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// request.hpp
|
||||
// ~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_REQUEST_HPP
|
||||
#define HTTP_SERVER3_REQUEST_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
/// A request received from a client.
|
||||
struct request
|
||||
{
|
||||
std::string method;
|
||||
std::string uri;
|
||||
int http_version_major;
|
||||
int http_version_minor;
|
||||
std::vector<header> headers;
|
||||
};
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_REQUEST_HPP
|
||||
122
asio/src/examples/cpp03/http/server3/request_handler.cpp
Normal file
122
asio/src/examples/cpp03/http/server3/request_handler.cpp
Normal file
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// request_handler.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_handler.hpp"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "mime_types.hpp"
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
request_handler::request_handler(const std::string& doc_root)
|
||||
: doc_root_(doc_root)
|
||||
{
|
||||
}
|
||||
|
||||
void request_handler::handle_request(const request& req, reply& rep)
|
||||
{
|
||||
// Decode url to path.
|
||||
std::string request_path;
|
||||
if (!url_decode(req.uri, request_path))
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// Request path must be absolute and not contain "..".
|
||||
if (request_path.empty() || request_path[0] != '/'
|
||||
|| request_path.find("..") != std::string::npos)
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// If path ends in slash (i.e. is a directory) then add "index.html".
|
||||
if (request_path[request_path.size() - 1] == '/')
|
||||
{
|
||||
request_path += "index.html";
|
||||
}
|
||||
|
||||
// Determine the file extension.
|
||||
std::size_t last_slash_pos = request_path.find_last_of("/");
|
||||
std::size_t last_dot_pos = request_path.find_last_of(".");
|
||||
std::string extension;
|
||||
if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos)
|
||||
{
|
||||
extension = request_path.substr(last_dot_pos + 1);
|
||||
}
|
||||
|
||||
// Open the file to send back.
|
||||
std::string full_path = doc_root_ + request_path;
|
||||
std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
|
||||
if (!is)
|
||||
{
|
||||
rep = reply::stock_reply(reply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill out the reply to be sent to the client.
|
||||
rep.status = reply::ok;
|
||||
char buf[512];
|
||||
while (is.read(buf, sizeof(buf)).gcount() > 0)
|
||||
rep.content.append(buf, is.gcount());
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = mime_types::extension_to_type(extension);
|
||||
}
|
||||
|
||||
bool request_handler::url_decode(const std::string& in, std::string& out)
|
||||
{
|
||||
out.clear();
|
||||
out.reserve(in.size());
|
||||
for (std::size_t i = 0; i < in.size(); ++i)
|
||||
{
|
||||
if (in[i] == '%')
|
||||
{
|
||||
if (i + 3 <= in.size())
|
||||
{
|
||||
int value = 0;
|
||||
std::istringstream is(in.substr(i + 1, 2));
|
||||
if (is >> std::hex >> value)
|
||||
{
|
||||
out += static_cast<char>(value);
|
||||
i += 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (in[i] == '+')
|
||||
{
|
||||
out += ' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
out += in[i];
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
46
asio/src/examples/cpp03/http/server3/request_handler.hpp
Normal file
46
asio/src/examples/cpp03/http/server3/request_handler.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// request_handler.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_REQUEST_HANDLER_HPP
|
||||
#define HTTP_SERVER3_REQUEST_HANDLER_HPP
|
||||
|
||||
#include <string>
|
||||
#include <boost/noncopyable.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
struct reply;
|
||||
struct request;
|
||||
|
||||
/// The common handler for all incoming requests.
|
||||
class request_handler
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct with a directory containing files to be served.
|
||||
explicit request_handler(const std::string& doc_root);
|
||||
|
||||
/// Handle a request and produce a reply.
|
||||
void handle_request(const request& req, reply& rep);
|
||||
|
||||
private:
|
||||
/// The directory containing the files to be served.
|
||||
std::string doc_root_;
|
||||
|
||||
/// Perform URL-decoding on a string. Returns false if the encoding was
|
||||
/// invalid.
|
||||
static bool url_decode(const std::string& in, std::string& out);
|
||||
};
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_REQUEST_HANDLER_HPP
|
||||
315
asio/src/examples/cpp03/http/server3/request_parser.cpp
Normal file
315
asio/src/examples/cpp03/http/server3/request_parser.cpp
Normal file
@@ -0,0 +1,315 @@
|
||||
//
|
||||
// request_parser.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_parser.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
request_parser::request_parser()
|
||||
: state_(method_start)
|
||||
{
|
||||
}
|
||||
|
||||
void request_parser::reset()
|
||||
{
|
||||
state_ = method_start;
|
||||
}
|
||||
|
||||
boost::tribool request_parser::consume(request& req, char input)
|
||||
{
|
||||
switch (state_)
|
||||
{
|
||||
case method_start:
|
||||
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = method;
|
||||
req.method.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case method:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = uri;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.method.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case uri:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = http_version_h;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.uri.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case http_version_h:
|
||||
if (input == 'H')
|
||||
{
|
||||
state_ = http_version_t_1;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_t_1:
|
||||
if (input == 'T')
|
||||
{
|
||||
state_ = http_version_t_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_t_2:
|
||||
if (input == 'T')
|
||||
{
|
||||
state_ = http_version_p;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_p:
|
||||
if (input == 'P')
|
||||
{
|
||||
state_ = http_version_slash;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_slash:
|
||||
if (input == '/')
|
||||
{
|
||||
req.http_version_major = 0;
|
||||
req.http_version_minor = 0;
|
||||
state_ = http_version_major_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_major_start:
|
||||
if (is_digit(input))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + input - '0';
|
||||
state_ = http_version_major;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_major:
|
||||
if (input == '.')
|
||||
{
|
||||
state_ = http_version_minor_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_digit(input))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + input - '0';
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_minor_start:
|
||||
if (is_digit(input))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + input - '0';
|
||||
state_ = http_version_minor;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case http_version_minor:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_1;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_digit(input))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + input - '0';
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case expecting_newline_1:
|
||||
if (input == '\n')
|
||||
{
|
||||
state_ = header_line_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case header_line_start:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_3;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!req.headers.empty() && (input == ' ' || input == '\t'))
|
||||
{
|
||||
state_ = header_lws;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.push_back(header());
|
||||
req.headers.back().name.push_back(input);
|
||||
state_ = header_name;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case header_lws:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (input == ' ' || input == '\t')
|
||||
{
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = header_value;
|
||||
req.headers.back().value.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case header_name:
|
||||
if (input == ':')
|
||||
{
|
||||
state_ = space_before_header_value;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.back().name.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case space_before_header_value:
|
||||
if (input == ' ')
|
||||
{
|
||||
state_ = header_value;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case header_value:
|
||||
if (input == '\r')
|
||||
{
|
||||
state_ = expecting_newline_2;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else if (is_ctl(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.headers.back().value.push_back(input);
|
||||
return boost::indeterminate;
|
||||
}
|
||||
case expecting_newline_2:
|
||||
if (input == '\n')
|
||||
{
|
||||
state_ = header_line_start;
|
||||
return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
case expecting_newline_3:
|
||||
return (input == '\n');
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_char(int c)
|
||||
{
|
||||
return c >= 0 && c <= 127;
|
||||
}
|
||||
|
||||
bool request_parser::is_ctl(int c)
|
||||
{
|
||||
return (c >= 0 && c <= 31) || (c == 127);
|
||||
}
|
||||
|
||||
bool request_parser::is_tspecial(int c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '(': case ')': case '<': case '>': case '@':
|
||||
case ',': case ';': case ':': case '\\': case '"':
|
||||
case '/': case '[': case ']': case '?': case '=':
|
||||
case '{': case '}': case ' ': case '\t':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_digit(int c)
|
||||
{
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
95
asio/src/examples/cpp03/http/server3/request_parser.hpp
Normal file
95
asio/src/examples/cpp03/http/server3/request_parser.hpp
Normal file
@@ -0,0 +1,95 @@
|
||||
//
|
||||
// request_parser.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_REQUEST_PARSER_HPP
|
||||
#define HTTP_SERVER3_REQUEST_PARSER_HPP
|
||||
|
||||
#include <boost/logic/tribool.hpp>
|
||||
#include <boost/tuple/tuple.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
struct request;
|
||||
|
||||
/// Parser for incoming requests.
|
||||
class request_parser
|
||||
{
|
||||
public:
|
||||
/// Construct ready to parse the request method.
|
||||
request_parser();
|
||||
|
||||
/// Reset to initial parser state.
|
||||
void reset();
|
||||
|
||||
/// Parse some data. The tribool return value is true when a complete request
|
||||
/// has been parsed, false if the data is invalid, indeterminate when more
|
||||
/// data is required. The InputIterator return value indicates how much of the
|
||||
/// input has been consumed.
|
||||
template <typename InputIterator>
|
||||
boost::tuple<boost::tribool, InputIterator> parse(request& req,
|
||||
InputIterator begin, InputIterator end)
|
||||
{
|
||||
while (begin != end)
|
||||
{
|
||||
boost::tribool result = consume(req, *begin++);
|
||||
if (result || !result)
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
boost::tribool result = boost::indeterminate;
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
|
||||
private:
|
||||
/// Handle the next character of input.
|
||||
boost::tribool consume(request& req, char input);
|
||||
|
||||
/// Check if a byte is an HTTP character.
|
||||
static bool is_char(int c);
|
||||
|
||||
/// Check if a byte is an HTTP control character.
|
||||
static bool is_ctl(int c);
|
||||
|
||||
/// Check if a byte is defined as an HTTP tspecial character.
|
||||
static bool is_tspecial(int c);
|
||||
|
||||
/// Check if a byte is a digit.
|
||||
static bool is_digit(int c);
|
||||
|
||||
/// The current state of the parser.
|
||||
enum state
|
||||
{
|
||||
method_start,
|
||||
method,
|
||||
uri,
|
||||
http_version_h,
|
||||
http_version_t_1,
|
||||
http_version_t_2,
|
||||
http_version_p,
|
||||
http_version_slash,
|
||||
http_version_major_start,
|
||||
http_version_major,
|
||||
http_version_minor_start,
|
||||
http_version_minor,
|
||||
expecting_newline_1,
|
||||
header_line_start,
|
||||
header_lws,
|
||||
header_name,
|
||||
space_before_header_value,
|
||||
header_value,
|
||||
expecting_newline_2,
|
||||
expecting_newline_3
|
||||
} state_;
|
||||
};
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_REQUEST_PARSER_HPP
|
||||
89
asio/src/examples/cpp03/http/server3/server.cpp
Normal file
89
asio/src/examples/cpp03/http/server3/server.cpp
Normal file
@@ -0,0 +1,89 @@
|
||||
//
|
||||
// server.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "server.hpp"
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <vector>
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
server::server(const std::string& address, const std::string& port,
|
||||
const std::string& doc_root, std::size_t thread_pool_size)
|
||||
: thread_pool_size_(thread_pool_size),
|
||||
signals_(io_context_),
|
||||
acceptor_(io_context_),
|
||||
new_connection_(),
|
||||
request_handler_(doc_root)
|
||||
{
|
||||
// Register to handle the signals that indicate when the server should exit.
|
||||
// It is safe to register for the same signal multiple times in a program,
|
||||
// provided all registration for the specified signal is made through Asio.
|
||||
signals_.add(SIGINT);
|
||||
signals_.add(SIGTERM);
|
||||
#if defined(SIGQUIT)
|
||||
signals_.add(SIGQUIT);
|
||||
#endif // defined(SIGQUIT)
|
||||
signals_.async_wait(boost::bind(&server::handle_stop, this));
|
||||
|
||||
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
|
||||
asio::ip::tcp::resolver resolver(io_context_);
|
||||
asio::ip::tcp::endpoint endpoint =
|
||||
*resolver.resolve(address, port).begin();
|
||||
acceptor_.open(endpoint.protocol());
|
||||
acceptor_.set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
||||
acceptor_.bind(endpoint);
|
||||
acceptor_.listen();
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void server::run()
|
||||
{
|
||||
// Create a pool of threads to run all of the io_contexts.
|
||||
std::vector<boost::shared_ptr<asio::thread> > threads;
|
||||
for (std::size_t i = 0; i < thread_pool_size_; ++i)
|
||||
{
|
||||
boost::shared_ptr<asio::thread> thread(new asio::thread(
|
||||
boost::bind(&asio::io_context::run, &io_context_)));
|
||||
threads.push_back(thread);
|
||||
}
|
||||
|
||||
// Wait for all threads in the pool to exit.
|
||||
for (std::size_t i = 0; i < threads.size(); ++i)
|
||||
threads[i]->join();
|
||||
}
|
||||
|
||||
void server::start_accept()
|
||||
{
|
||||
new_connection_.reset(new connection(io_context_, request_handler_));
|
||||
acceptor_.async_accept(new_connection_->socket(),
|
||||
boost::bind(&server::handle_accept, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void server::handle_accept(const asio::error_code& e)
|
||||
{
|
||||
if (!e)
|
||||
{
|
||||
new_connection_->start();
|
||||
}
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
void server::handle_stop()
|
||||
{
|
||||
io_context_.stop();
|
||||
}
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
70
asio/src/examples/cpp03/http/server3/server.hpp
Normal file
70
asio/src/examples/cpp03/http/server3/server.hpp
Normal file
@@ -0,0 +1,70 @@
|
||||
//
|
||||
// server.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER3_SERVER_HPP
|
||||
#define HTTP_SERVER3_SERVER_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <boost/noncopyable.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include "connection.hpp"
|
||||
#include "request_handler.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server3 {
|
||||
|
||||
/// The top-level class of the HTTP server.
|
||||
class server
|
||||
: private boost::noncopyable
|
||||
{
|
||||
public:
|
||||
/// Construct the server to listen on the specified TCP address and port, and
|
||||
/// serve up files from the given directory.
|
||||
explicit server(const std::string& address, const std::string& port,
|
||||
const std::string& doc_root, std::size_t thread_pool_size);
|
||||
|
||||
/// Run the server's io_context loop.
|
||||
void run();
|
||||
|
||||
private:
|
||||
/// Initiate an asynchronous accept operation.
|
||||
void start_accept();
|
||||
|
||||
/// Handle completion of an asynchronous accept operation.
|
||||
void handle_accept(const asio::error_code& e);
|
||||
|
||||
/// Handle a request to stop the server.
|
||||
void handle_stop();
|
||||
|
||||
/// The number of threads that will call io_context::run().
|
||||
std::size_t thread_pool_size_;
|
||||
|
||||
/// The io_context used to perform asynchronous operations.
|
||||
asio::io_context io_context_;
|
||||
|
||||
/// The signal_set is used to register for process termination notifications.
|
||||
asio::signal_set signals_;
|
||||
|
||||
/// Acceptor used to listen for incoming connections.
|
||||
asio::ip::tcp::acceptor acceptor_;
|
||||
|
||||
/// The next connection to be accepted.
|
||||
connection_ptr new_connection_;
|
||||
|
||||
/// The handler for all incoming requests.
|
||||
request_handler request_handler_;
|
||||
};
|
||||
|
||||
} // namespace server3
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER3_SERVER_HPP
|
||||
122
asio/src/examples/cpp03/http/server4/file_handler.cpp
Normal file
122
asio/src/examples/cpp03/http/server4/file_handler.cpp
Normal file
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// file_handler.cpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "file_handler.hpp"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "mime_types.hpp"
|
||||
#include "reply.hpp"
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
file_handler::file_handler(const std::string& doc_root)
|
||||
: doc_root_(doc_root)
|
||||
{
|
||||
}
|
||||
|
||||
void file_handler::operator()(const request& req, reply& rep)
|
||||
{
|
||||
// Decode url to path.
|
||||
std::string request_path;
|
||||
if (!url_decode(req.uri, request_path))
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// Request path must be absolute and not contain "..".
|
||||
if (request_path.empty() || request_path[0] != '/'
|
||||
|| request_path.find("..") != std::string::npos)
|
||||
{
|
||||
rep = reply::stock_reply(reply::bad_request);
|
||||
return;
|
||||
}
|
||||
|
||||
// If path ends in slash (i.e. is a directory) then add "index.html".
|
||||
if (request_path[request_path.size() - 1] == '/')
|
||||
{
|
||||
request_path += "index.html";
|
||||
}
|
||||
|
||||
// Determine the file extension.
|
||||
std::size_t last_slash_pos = request_path.find_last_of("/");
|
||||
std::size_t last_dot_pos = request_path.find_last_of(".");
|
||||
std::string extension;
|
||||
if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos)
|
||||
{
|
||||
extension = request_path.substr(last_dot_pos + 1);
|
||||
}
|
||||
|
||||
// Open the file to send back.
|
||||
std::string full_path = doc_root_ + request_path;
|
||||
std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
|
||||
if (!is)
|
||||
{
|
||||
rep = reply::stock_reply(reply::not_found);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill out the reply to be sent to the client.
|
||||
rep.status = reply::ok;
|
||||
char buf[512];
|
||||
while (is.read(buf, sizeof(buf)).gcount() > 0)
|
||||
rep.content.append(buf, is.gcount());
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = mime_types::extension_to_type(extension);
|
||||
}
|
||||
|
||||
bool file_handler::url_decode(const std::string& in, std::string& out)
|
||||
{
|
||||
out.clear();
|
||||
out.reserve(in.size());
|
||||
for (std::size_t i = 0; i < in.size(); ++i)
|
||||
{
|
||||
if (in[i] == '%')
|
||||
{
|
||||
if (i + 3 <= in.size())
|
||||
{
|
||||
int value = 0;
|
||||
std::istringstream is(in.substr(i + 1, 2));
|
||||
if (is >> std::hex >> value)
|
||||
{
|
||||
out += static_cast<char>(value);
|
||||
i += 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (in[i] == '+')
|
||||
{
|
||||
out += ' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
out += in[i];
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
44
asio/src/examples/cpp03/http/server4/file_handler.hpp
Normal file
44
asio/src/examples/cpp03/http/server4/file_handler.hpp
Normal file
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// file_handler.hpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_FILE_HANDLER_HPP
|
||||
#define HTTP_SERVER4_FILE_HANDLER_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
struct reply;
|
||||
struct request;
|
||||
|
||||
/// The common handler for all incoming requests.
|
||||
class file_handler
|
||||
{
|
||||
public:
|
||||
/// Construct with a directory containing files to be served.
|
||||
explicit file_handler(const std::string& doc_root);
|
||||
|
||||
/// Handle a request and produce a reply.
|
||||
void operator()(const request& req, reply& rep);
|
||||
|
||||
private:
|
||||
/// The directory containing the files to be served.
|
||||
std::string doc_root_;
|
||||
|
||||
/// Perform URL-decoding on a string. Returns false if the encoding was
|
||||
/// invalid.
|
||||
static bool url_decode(const std::string& in, std::string& out);
|
||||
};
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_FILE_HANDLER_HPP
|
||||
28
asio/src/examples/cpp03/http/server4/header.hpp
Normal file
28
asio/src/examples/cpp03/http/server4/header.hpp
Normal file
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// header.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_HEADER_HPP
|
||||
#define HTTP_SERVER4_HEADER_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
struct header
|
||||
{
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_HEADER_HPP
|
||||
58
asio/src/examples/cpp03/http/server4/main.cpp
Normal file
58
asio/src/examples/cpp03/http/server4/main.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
//
|
||||
// main.cpp
|
||||
// ~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <signal.h>
|
||||
#include "server.hpp"
|
||||
#include "file_handler.hpp"
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check command line arguments.
|
||||
if (argc != 4)
|
||||
{
|
||||
std::cerr << "Usage: http_server <address> <port> <doc_root>\n";
|
||||
std::cerr << " For IPv4, try:\n";
|
||||
std::cerr << " receiver 0.0.0.0 80 .\n";
|
||||
std::cerr << " For IPv6, try:\n";
|
||||
std::cerr << " receiver 0::0 80 .\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
// Launch the initial server coroutine.
|
||||
http::server4::server(io_context, argv[1], argv[2],
|
||||
http::server4::file_handler(argv[3]))();
|
||||
|
||||
// Wait for signals indicating time to shut down.
|
||||
asio::signal_set signals(io_context);
|
||||
signals.add(SIGINT);
|
||||
signals.add(SIGTERM);
|
||||
#if defined(SIGQUIT)
|
||||
signals.add(SIGQUIT);
|
||||
#endif // defined(SIGQUIT)
|
||||
signals.async_wait(boost::bind(
|
||||
&asio::io_context::stop, &io_context));
|
||||
|
||||
// Run the server.
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
46
asio/src/examples/cpp03/http/server4/mime_types.cpp
Normal file
46
asio/src/examples/cpp03/http/server4/mime_types.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// mime_types.cpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "mime_types.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
namespace mime_types {
|
||||
|
||||
struct mapping
|
||||
{
|
||||
const char* extension;
|
||||
const char* mime_type;
|
||||
} mappings[] =
|
||||
{
|
||||
{ "gif", "image/gif" },
|
||||
{ "htm", "text/html" },
|
||||
{ "html", "text/html" },
|
||||
{ "jpg", "image/jpeg" },
|
||||
{ "png", "image/png" },
|
||||
{ 0, 0 } // Marks end of list.
|
||||
};
|
||||
|
||||
std::string extension_to_type(const std::string& extension)
|
||||
{
|
||||
for (mapping* m = mappings; m->extension; ++m)
|
||||
{
|
||||
if (m->extension == extension)
|
||||
{
|
||||
return m->mime_type;
|
||||
}
|
||||
}
|
||||
|
||||
return "text/plain";
|
||||
}
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
27
asio/src/examples/cpp03/http/server4/mime_types.hpp
Normal file
27
asio/src/examples/cpp03/http/server4/mime_types.hpp
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// mime_types.hpp
|
||||
// ~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_MIME_TYPES_HPP
|
||||
#define HTTP_SERVER4_MIME_TYPES_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
namespace mime_types {
|
||||
|
||||
/// Convert a file extension into a MIME type.
|
||||
std::string extension_to_type(const std::string& extension);
|
||||
|
||||
} // namespace mime_types
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_MIME_TYPES_HPP
|
||||
256
asio/src/examples/cpp03/http/server4/reply.cpp
Normal file
256
asio/src/examples/cpp03/http/server4/reply.cpp
Normal file
@@ -0,0 +1,256 @@
|
||||
//
|
||||
// reply.cpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "reply.hpp"
|
||||
#include <string>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
namespace status_strings {
|
||||
|
||||
const std::string ok =
|
||||
"HTTP/1.0 200 OK\r\n";
|
||||
const std::string created =
|
||||
"HTTP/1.0 201 Created\r\n";
|
||||
const std::string accepted =
|
||||
"HTTP/1.0 202 Accepted\r\n";
|
||||
const std::string no_content =
|
||||
"HTTP/1.0 204 No Content\r\n";
|
||||
const std::string multiple_choices =
|
||||
"HTTP/1.0 300 Multiple Choices\r\n";
|
||||
const std::string moved_permanently =
|
||||
"HTTP/1.0 301 Moved Permanently\r\n";
|
||||
const std::string moved_temporarily =
|
||||
"HTTP/1.0 302 Moved Temporarily\r\n";
|
||||
const std::string not_modified =
|
||||
"HTTP/1.0 304 Not Modified\r\n";
|
||||
const std::string bad_request =
|
||||
"HTTP/1.0 400 Bad Request\r\n";
|
||||
const std::string unauthorized =
|
||||
"HTTP/1.0 401 Unauthorized\r\n";
|
||||
const std::string forbidden =
|
||||
"HTTP/1.0 403 Forbidden\r\n";
|
||||
const std::string not_found =
|
||||
"HTTP/1.0 404 Not Found\r\n";
|
||||
const std::string internal_server_error =
|
||||
"HTTP/1.0 500 Internal Server Error\r\n";
|
||||
const std::string not_implemented =
|
||||
"HTTP/1.0 501 Not Implemented\r\n";
|
||||
const std::string bad_gateway =
|
||||
"HTTP/1.0 502 Bad Gateway\r\n";
|
||||
const std::string service_unavailable =
|
||||
"HTTP/1.0 503 Service Unavailable\r\n";
|
||||
|
||||
asio::const_buffer to_buffer(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return asio::buffer(ok);
|
||||
case reply::created:
|
||||
return asio::buffer(created);
|
||||
case reply::accepted:
|
||||
return asio::buffer(accepted);
|
||||
case reply::no_content:
|
||||
return asio::buffer(no_content);
|
||||
case reply::multiple_choices:
|
||||
return asio::buffer(multiple_choices);
|
||||
case reply::moved_permanently:
|
||||
return asio::buffer(moved_permanently);
|
||||
case reply::moved_temporarily:
|
||||
return asio::buffer(moved_temporarily);
|
||||
case reply::not_modified:
|
||||
return asio::buffer(not_modified);
|
||||
case reply::bad_request:
|
||||
return asio::buffer(bad_request);
|
||||
case reply::unauthorized:
|
||||
return asio::buffer(unauthorized);
|
||||
case reply::forbidden:
|
||||
return asio::buffer(forbidden);
|
||||
case reply::not_found:
|
||||
return asio::buffer(not_found);
|
||||
case reply::internal_server_error:
|
||||
return asio::buffer(internal_server_error);
|
||||
case reply::not_implemented:
|
||||
return asio::buffer(not_implemented);
|
||||
case reply::bad_gateway:
|
||||
return asio::buffer(bad_gateway);
|
||||
case reply::service_unavailable:
|
||||
return asio::buffer(service_unavailable);
|
||||
default:
|
||||
return asio::buffer(internal_server_error);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace status_strings
|
||||
|
||||
namespace misc_strings {
|
||||
|
||||
const char name_value_separator[] = { ':', ' ' };
|
||||
const char crlf[] = { '\r', '\n' };
|
||||
|
||||
} // namespace misc_strings
|
||||
|
||||
std::vector<asio::const_buffer> reply::to_buffers()
|
||||
{
|
||||
std::vector<asio::const_buffer> buffers;
|
||||
buffers.push_back(status_strings::to_buffer(status));
|
||||
for (std::size_t i = 0; i < headers.size(); ++i)
|
||||
{
|
||||
header& h = headers[i];
|
||||
buffers.push_back(asio::buffer(h.name));
|
||||
buffers.push_back(asio::buffer(misc_strings::name_value_separator));
|
||||
buffers.push_back(asio::buffer(h.value));
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
}
|
||||
buffers.push_back(asio::buffer(misc_strings::crlf));
|
||||
buffers.push_back(asio::buffer(content));
|
||||
return buffers;
|
||||
}
|
||||
|
||||
namespace stock_replies {
|
||||
|
||||
const char ok[] = "";
|
||||
const char created[] =
|
||||
"<html>"
|
||||
"<head><title>Created</title></head>"
|
||||
"<body><h1>201 Created</h1></body>"
|
||||
"</html>";
|
||||
const char accepted[] =
|
||||
"<html>"
|
||||
"<head><title>Accepted</title></head>"
|
||||
"<body><h1>202 Accepted</h1></body>"
|
||||
"</html>";
|
||||
const char no_content[] =
|
||||
"<html>"
|
||||
"<head><title>No Content</title></head>"
|
||||
"<body><h1>204 Content</h1></body>"
|
||||
"</html>";
|
||||
const char multiple_choices[] =
|
||||
"<html>"
|
||||
"<head><title>Multiple Choices</title></head>"
|
||||
"<body><h1>300 Multiple Choices</h1></body>"
|
||||
"</html>";
|
||||
const char moved_permanently[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Permanently</title></head>"
|
||||
"<body><h1>301 Moved Permanently</h1></body>"
|
||||
"</html>";
|
||||
const char moved_temporarily[] =
|
||||
"<html>"
|
||||
"<head><title>Moved Temporarily</title></head>"
|
||||
"<body><h1>302 Moved Temporarily</h1></body>"
|
||||
"</html>";
|
||||
const char not_modified[] =
|
||||
"<html>"
|
||||
"<head><title>Not Modified</title></head>"
|
||||
"<body><h1>304 Not Modified</h1></body>"
|
||||
"</html>";
|
||||
const char bad_request[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Request</title></head>"
|
||||
"<body><h1>400 Bad Request</h1></body>"
|
||||
"</html>";
|
||||
const char unauthorized[] =
|
||||
"<html>"
|
||||
"<head><title>Unauthorized</title></head>"
|
||||
"<body><h1>401 Unauthorized</h1></body>"
|
||||
"</html>";
|
||||
const char forbidden[] =
|
||||
"<html>"
|
||||
"<head><title>Forbidden</title></head>"
|
||||
"<body><h1>403 Forbidden</h1></body>"
|
||||
"</html>";
|
||||
const char not_found[] =
|
||||
"<html>"
|
||||
"<head><title>Not Found</title></head>"
|
||||
"<body><h1>404 Not Found</h1></body>"
|
||||
"</html>";
|
||||
const char internal_server_error[] =
|
||||
"<html>"
|
||||
"<head><title>Internal Server Error</title></head>"
|
||||
"<body><h1>500 Internal Server Error</h1></body>"
|
||||
"</html>";
|
||||
const char not_implemented[] =
|
||||
"<html>"
|
||||
"<head><title>Not Implemented</title></head>"
|
||||
"<body><h1>501 Not Implemented</h1></body>"
|
||||
"</html>";
|
||||
const char bad_gateway[] =
|
||||
"<html>"
|
||||
"<head><title>Bad Gateway</title></head>"
|
||||
"<body><h1>502 Bad Gateway</h1></body>"
|
||||
"</html>";
|
||||
const char service_unavailable[] =
|
||||
"<html>"
|
||||
"<head><title>Service Unavailable</title></head>"
|
||||
"<body><h1>503 Service Unavailable</h1></body>"
|
||||
"</html>";
|
||||
|
||||
std::string to_string(reply::status_type status)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case reply::ok:
|
||||
return ok;
|
||||
case reply::created:
|
||||
return created;
|
||||
case reply::accepted:
|
||||
return accepted;
|
||||
case reply::no_content:
|
||||
return no_content;
|
||||
case reply::multiple_choices:
|
||||
return multiple_choices;
|
||||
case reply::moved_permanently:
|
||||
return moved_permanently;
|
||||
case reply::moved_temporarily:
|
||||
return moved_temporarily;
|
||||
case reply::not_modified:
|
||||
return not_modified;
|
||||
case reply::bad_request:
|
||||
return bad_request;
|
||||
case reply::unauthorized:
|
||||
return unauthorized;
|
||||
case reply::forbidden:
|
||||
return forbidden;
|
||||
case reply::not_found:
|
||||
return not_found;
|
||||
case reply::internal_server_error:
|
||||
return internal_server_error;
|
||||
case reply::not_implemented:
|
||||
return not_implemented;
|
||||
case reply::bad_gateway:
|
||||
return bad_gateway;
|
||||
case reply::service_unavailable:
|
||||
return service_unavailable;
|
||||
default:
|
||||
return internal_server_error;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace stock_replies
|
||||
|
||||
reply reply::stock_reply(reply::status_type status)
|
||||
{
|
||||
reply rep;
|
||||
rep.status = status;
|
||||
rep.content = stock_replies::to_string(status);
|
||||
rep.headers.resize(2);
|
||||
rep.headers[0].name = "Content-Length";
|
||||
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
|
||||
rep.headers[1].name = "Content-Type";
|
||||
rep.headers[1].value = "text/html";
|
||||
return rep;
|
||||
}
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
64
asio/src/examples/cpp03/http/server4/reply.hpp
Normal file
64
asio/src/examples/cpp03/http/server4/reply.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// reply.hpp
|
||||
// ~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_REPLY_HPP
|
||||
#define HTTP_SERVER4_REPLY_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <asio.hpp>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
/// A reply to be sent to a client.
|
||||
struct reply
|
||||
{
|
||||
/// The status of the reply.
|
||||
enum status_type
|
||||
{
|
||||
ok = 200,
|
||||
created = 201,
|
||||
accepted = 202,
|
||||
no_content = 204,
|
||||
multiple_choices = 300,
|
||||
moved_permanently = 301,
|
||||
moved_temporarily = 302,
|
||||
not_modified = 304,
|
||||
bad_request = 400,
|
||||
unauthorized = 401,
|
||||
forbidden = 403,
|
||||
not_found = 404,
|
||||
internal_server_error = 500,
|
||||
not_implemented = 501,
|
||||
bad_gateway = 502,
|
||||
service_unavailable = 503
|
||||
} status;
|
||||
|
||||
/// The headers to be included in the reply.
|
||||
std::vector<header> headers;
|
||||
|
||||
/// The content to be sent in the reply.
|
||||
std::string content;
|
||||
|
||||
/// Convert the reply into a vector of buffers. The buffers do not own the
|
||||
/// underlying memory blocks, therefore the reply object must remain valid and
|
||||
/// not be changed until the write operation has completed.
|
||||
std::vector<asio::const_buffer> to_buffers();
|
||||
|
||||
/// Get a stock reply.
|
||||
static reply stock_reply(status_type status);
|
||||
};
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_REPLY_HPP
|
||||
46
asio/src/examples/cpp03/http/server4/request.hpp
Normal file
46
asio/src/examples/cpp03/http/server4/request.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// request.hpp
|
||||
// ~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_REQUEST_HPP
|
||||
#define HTTP_SERVER4_REQUEST_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "header.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
/// A request received from a client.
|
||||
struct request
|
||||
{
|
||||
/// The request method, e.g. "GET", "POST".
|
||||
std::string method;
|
||||
|
||||
/// The requested URI, such as a path to a file.
|
||||
std::string uri;
|
||||
|
||||
/// Major version number, usually 1.
|
||||
int http_version_major;
|
||||
|
||||
/// Minor version number, usually 0 or 1.
|
||||
int http_version_minor;
|
||||
|
||||
/// The headers included with the request.
|
||||
std::vector<header> headers;
|
||||
|
||||
/// The optional content sent with the request.
|
||||
std::string content;
|
||||
};
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_REQUEST_HPP
|
||||
226
asio/src/examples/cpp03/http/server4/request_parser.cpp
Normal file
226
asio/src/examples/cpp03/http/server4/request_parser.cpp
Normal file
@@ -0,0 +1,226 @@
|
||||
//
|
||||
// request_parser.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "request_parser.hpp"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
#include "request.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
// Enable the pseudo-keywords reenter, yield and fork.
|
||||
#include <asio/yield.hpp>
|
||||
|
||||
std::string request_parser::content_length_name_ = "Content-Length";
|
||||
|
||||
boost::tribool request_parser::consume(request& req, char c)
|
||||
{
|
||||
reenter (this)
|
||||
{
|
||||
req.method.clear();
|
||||
req.uri.clear();
|
||||
req.http_version_major = 0;
|
||||
req.http_version_minor = 0;
|
||||
req.headers.clear();
|
||||
req.content.clear();
|
||||
content_length_ = 0;
|
||||
|
||||
// Request method.
|
||||
while (is_char(c) && !is_ctl(c) && !is_tspecial(c) && c != ' ')
|
||||
{
|
||||
req.method.push_back(c);
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
if (req.method.empty())
|
||||
return false;
|
||||
|
||||
// Space.
|
||||
if (c != ' ') return false;
|
||||
yield return boost::indeterminate;
|
||||
|
||||
// URI.
|
||||
while (!is_ctl(c) && c != ' ')
|
||||
{
|
||||
req.uri.push_back(c);
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
if (req.uri.empty()) return false;
|
||||
|
||||
// Space.
|
||||
if (c != ' ') return false;
|
||||
yield return boost::indeterminate;
|
||||
|
||||
// HTTP protocol identifier.
|
||||
if (c != 'H') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != 'T') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != 'T') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != 'P') return false;
|
||||
yield return boost::indeterminate;
|
||||
|
||||
// Slash.
|
||||
if (c != '/') return false;
|
||||
yield return boost::indeterminate;
|
||||
|
||||
// Major version number.
|
||||
if (!is_digit(c)) return false;
|
||||
while (is_digit(c))
|
||||
{
|
||||
req.http_version_major = req.http_version_major * 10 + c - '0';
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
|
||||
// Dot.
|
||||
if (c != '.') return false;
|
||||
yield return boost::indeterminate;
|
||||
|
||||
// Minor version number.
|
||||
if (!is_digit(c)) return false;
|
||||
while (is_digit(c))
|
||||
{
|
||||
req.http_version_minor = req.http_version_minor * 10 + c - '0';
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
|
||||
// CRLF.
|
||||
if (c != '\r') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != '\n') return false;
|
||||
yield return boost::indeterminate;
|
||||
|
||||
// Headers.
|
||||
while ((is_char(c) && !is_ctl(c) && !is_tspecial(c) && c != '\r')
|
||||
|| (c == ' ' || c == '\t'))
|
||||
{
|
||||
if (c == ' ' || c == '\t')
|
||||
{
|
||||
// Leading whitespace. Must be continuation of previous header's value.
|
||||
if (req.headers.empty()) return false;
|
||||
while (c == ' ' || c == '\t')
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Start the next header.
|
||||
req.headers.push_back(header());
|
||||
|
||||
// Header name.
|
||||
while (is_char(c) && !is_ctl(c) && !is_tspecial(c) && c != ':')
|
||||
{
|
||||
req.headers.back().name.push_back(c);
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
|
||||
// Colon and space separates the header name from the header value.
|
||||
if (c != ':') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != ' ') return false;
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
|
||||
// Header value.
|
||||
while (is_char(c) && !is_ctl(c) && c != '\r')
|
||||
{
|
||||
req.headers.back().value.push_back(c);
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
|
||||
// CRLF.
|
||||
if (c != '\r') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != '\n') return false;
|
||||
yield return boost::indeterminate;
|
||||
}
|
||||
|
||||
// CRLF.
|
||||
if (c != '\r') return false;
|
||||
yield return boost::indeterminate;
|
||||
if (c != '\n') return false;
|
||||
|
||||
// Check for optional Content-Length header.
|
||||
for (std::size_t i = 0; i < req.headers.size(); ++i)
|
||||
{
|
||||
if (headers_equal(req.headers[i].name, content_length_name_))
|
||||
{
|
||||
try
|
||||
{
|
||||
content_length_ =
|
||||
boost::lexical_cast<std::size_t>(req.headers[i].value);
|
||||
}
|
||||
catch (boost::bad_lexical_cast&)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Content.
|
||||
while (req.content.size() < content_length_)
|
||||
{
|
||||
yield return boost::indeterminate;
|
||||
req.content.push_back(c);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Disable the pseudo-keywords reenter, yield and fork.
|
||||
#include <asio/unyield.hpp>
|
||||
|
||||
bool request_parser::is_char(int c)
|
||||
{
|
||||
return c >= 0 && c <= 127;
|
||||
}
|
||||
|
||||
bool request_parser::is_ctl(int c)
|
||||
{
|
||||
return (c >= 0 && c <= 31) || (c == 127);
|
||||
}
|
||||
|
||||
bool request_parser::is_tspecial(int c)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '(': case ')': case '<': case '>': case '@':
|
||||
case ',': case ';': case ':': case '\\': case '"':
|
||||
case '/': case '[': case ']': case '?': case '=':
|
||||
case '{': case '}': case ' ': case '\t':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool request_parser::is_digit(int c)
|
||||
{
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
|
||||
bool request_parser::tolower_compare(char a, char b)
|
||||
{
|
||||
return std::tolower(a) == std::tolower(b);
|
||||
}
|
||||
|
||||
bool request_parser::headers_equal(const std::string& a, const std::string& b)
|
||||
{
|
||||
if (a.length() != b.length())
|
||||
return false;
|
||||
|
||||
return std::equal(a.begin(), a.end(), b.begin(),
|
||||
&request_parser::tolower_compare);
|
||||
}
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
78
asio/src/examples/cpp03/http/server4/request_parser.hpp
Normal file
78
asio/src/examples/cpp03/http/server4/request_parser.hpp
Normal file
@@ -0,0 +1,78 @@
|
||||
//
|
||||
// request_parser.hpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_REQUEST_PARSER_HPP
|
||||
#define HTTP_SERVER4_REQUEST_PARSER_HPP
|
||||
|
||||
#include <string>
|
||||
#include <boost/logic/tribool.hpp>
|
||||
#include <boost/tuple/tuple.hpp>
|
||||
#include <asio/coroutine.hpp>
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
struct request;
|
||||
|
||||
/// Parser for incoming requests.
|
||||
class request_parser : asio::coroutine
|
||||
{
|
||||
public:
|
||||
/// Parse some data. The tribool return value is true when a complete request
|
||||
/// has been parsed, false if the data is invalid, indeterminate when more
|
||||
/// data is required. The InputIterator return value indicates how much of the
|
||||
/// input has been consumed.
|
||||
template <typename InputIterator>
|
||||
boost::tuple<boost::tribool, InputIterator> parse(request& req,
|
||||
InputIterator begin, InputIterator end)
|
||||
{
|
||||
while (begin != end)
|
||||
{
|
||||
boost::tribool result = consume(req, *begin++);
|
||||
if (result || !result)
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
boost::tribool result = boost::indeterminate;
|
||||
return boost::make_tuple(result, begin);
|
||||
}
|
||||
|
||||
private:
|
||||
/// The name of the content length header.
|
||||
static std::string content_length_name_;
|
||||
|
||||
/// Content length as decoded from headers. Defaults to 0.
|
||||
std::size_t content_length_;
|
||||
|
||||
/// Handle the next character of input.
|
||||
boost::tribool consume(request& req, char input);
|
||||
|
||||
/// Check if a byte is an HTTP character.
|
||||
static bool is_char(int c);
|
||||
|
||||
/// Check if a byte is an HTTP control character.
|
||||
static bool is_ctl(int c);
|
||||
|
||||
/// Check if a byte is defined as an HTTP tspecial character.
|
||||
static bool is_tspecial(int c);
|
||||
|
||||
/// Check if a byte is a digit.
|
||||
static bool is_digit(int c);
|
||||
|
||||
/// Check if two characters are equal, without regard to case.
|
||||
static bool tolower_compare(char a, char b);
|
||||
|
||||
/// Check whether the two request header names match.
|
||||
bool headers_equal(const std::string& a, const std::string& b);
|
||||
};
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_REQUEST_PARSER_HPP
|
||||
122
asio/src/examples/cpp03/http/server4/server.cpp
Normal file
122
asio/src/examples/cpp03/http/server4/server.cpp
Normal file
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// server.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "server.hpp"
|
||||
#include "request.hpp"
|
||||
#include "reply.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
server::server(asio::io_context& io_context,
|
||||
const std::string& address, const std::string& port,
|
||||
boost::function<void(const request&, reply&)> request_handler)
|
||||
: request_handler_(request_handler)
|
||||
{
|
||||
tcp::resolver resolver(io_context);
|
||||
asio::ip::tcp::endpoint endpoint =
|
||||
*resolver.resolve(address, port).begin();
|
||||
acceptor_.reset(new tcp::acceptor(io_context, endpoint));
|
||||
}
|
||||
|
||||
// Enable the pseudo-keywords reenter, yield and fork.
|
||||
#include <asio/yield.hpp>
|
||||
|
||||
void server::operator()(asio::error_code ec, std::size_t length)
|
||||
{
|
||||
// In this example we keep the error handling code in one place by
|
||||
// hoisting it outside the coroutine. An alternative approach would be to
|
||||
// check the value of ec after each yield for an asynchronous operation.
|
||||
if (!ec)
|
||||
{
|
||||
// On reentering a coroutine, control jumps to the location of the last
|
||||
// yield or fork. The argument to the "reenter" pseudo-keyword can be a
|
||||
// pointer or reference to an object of type coroutine.
|
||||
reenter (this)
|
||||
{
|
||||
// Loop to accept incoming connections.
|
||||
do
|
||||
{
|
||||
// Create a new socket for the next incoming connection.
|
||||
socket_.reset(new tcp::socket(acceptor_->get_executor()));
|
||||
|
||||
// Accept a new connection. The "yield" pseudo-keyword saves the current
|
||||
// line number and exits the coroutine's "reenter" block. We use the
|
||||
// server coroutine as the completion handler for the async_accept
|
||||
// operation. When the asynchronous operation completes, the io_context
|
||||
// invokes the function call operator, we "reenter" the coroutine, and
|
||||
// then control resumes at the following line.
|
||||
yield acceptor_->async_accept(*socket_, *this);
|
||||
|
||||
// We "fork" by cloning a new server coroutine to handle the connection.
|
||||
// After forking we have a parent coroutine and a child coroutine. Both
|
||||
// parent and child continue execution at the following line. They can
|
||||
// be distinguished using the functions coroutine::is_parent() and
|
||||
// coroutine::is_child().
|
||||
fork server(*this)();
|
||||
|
||||
// The parent continues looping to accept the next incoming connection.
|
||||
// The child exits the loop and processes the connection.
|
||||
} while (is_parent());
|
||||
|
||||
// Create the objects needed to receive a request on the connection.
|
||||
buffer_.reset(new boost::array<char, 8192>);
|
||||
request_.reset(new request);
|
||||
|
||||
// Loop until a complete request (or an invalid one) has been received.
|
||||
do
|
||||
{
|
||||
// Receive some more data. When control resumes at the following line,
|
||||
// the ec and length parameters reflect the result of the asynchronous
|
||||
// operation.
|
||||
yield socket_->async_read_some(asio::buffer(*buffer_), *this);
|
||||
|
||||
// Parse the data we just received.
|
||||
boost::tie(valid_request_, boost::tuples::ignore)
|
||||
= request_parser_.parse(*request_,
|
||||
buffer_->data(), buffer_->data() + length);
|
||||
|
||||
// An indeterminate result means we need more data, so keep looping.
|
||||
} while (boost::indeterminate(valid_request_));
|
||||
|
||||
// Create the reply object that will be sent back to the client.
|
||||
reply_.reset(new reply);
|
||||
|
||||
if (valid_request_)
|
||||
{
|
||||
// A valid request was received. Call the user-supplied function object
|
||||
// to process the request and compose a reply.
|
||||
request_handler_(*request_, *reply_);
|
||||
}
|
||||
else
|
||||
{
|
||||
// The request was invalid.
|
||||
*reply_ = reply::stock_reply(reply::bad_request);
|
||||
}
|
||||
|
||||
// Send the reply back to the client.
|
||||
yield asio::async_write(*socket_, reply_->to_buffers(), *this);
|
||||
|
||||
// Initiate graceful connection closure.
|
||||
socket_->shutdown(tcp::socket::shutdown_both, ec);
|
||||
}
|
||||
}
|
||||
|
||||
// If an error occurs then the coroutine is not reentered. Consequently, no
|
||||
// new asynchronous operations are started. This means that all shared_ptr
|
||||
// references will disappear and the resources associated with the coroutine
|
||||
// will be destroyed automatically after this function call returns.
|
||||
}
|
||||
|
||||
// Disable the pseudo-keywords reenter, yield and fork.
|
||||
#include <asio/unyield.hpp>
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
73
asio/src/examples/cpp03/http/server4/server.hpp
Normal file
73
asio/src/examples/cpp03/http/server4/server.hpp
Normal file
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// server.hpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef HTTP_SERVER4_SERVER_HPP
|
||||
#define HTTP_SERVER4_SERVER_HPP
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <string>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include "request_parser.hpp"
|
||||
|
||||
namespace http {
|
||||
namespace server4 {
|
||||
|
||||
struct request;
|
||||
struct reply;
|
||||
|
||||
/// The top-level coroutine of the HTTP server.
|
||||
class server : asio::coroutine
|
||||
{
|
||||
public:
|
||||
/// Construct the server to listen on the specified TCP address and port, and
|
||||
/// serve up files from the given directory.
|
||||
explicit server(asio::io_context& io_context,
|
||||
const std::string& address, const std::string& port,
|
||||
boost::function<void(const request&, reply&)> request_handler);
|
||||
|
||||
/// Perform work associated with the server.
|
||||
void operator()(
|
||||
asio::error_code ec = asio::error_code(),
|
||||
std::size_t length = 0);
|
||||
|
||||
private:
|
||||
typedef asio::ip::tcp tcp;
|
||||
|
||||
/// The user-supplied handler for all incoming requests.
|
||||
boost::function<void(const request&, reply&)> request_handler_;
|
||||
|
||||
/// Acceptor used to listen for incoming connections.
|
||||
boost::shared_ptr<tcp::acceptor> acceptor_;
|
||||
|
||||
/// The current connection from a client.
|
||||
boost::shared_ptr<tcp::socket> socket_;
|
||||
|
||||
/// Buffer for incoming data.
|
||||
boost::shared_ptr<boost::array<char, 8192> > buffer_;
|
||||
|
||||
/// The incoming request.
|
||||
boost::shared_ptr<request> request_;
|
||||
|
||||
/// Whether the request is valid or not.
|
||||
boost::tribool valid_request_;
|
||||
|
||||
/// The parser for the incoming request.
|
||||
request_parser request_parser_;
|
||||
|
||||
/// The reply to be sent back to the client.
|
||||
boost::shared_ptr<reply> reply_;
|
||||
};
|
||||
|
||||
} // namespace server4
|
||||
} // namespace http
|
||||
|
||||
#endif // HTTP_SERVER4_SERVER_HPP
|
||||
94
asio/src/examples/cpp03/icmp/icmp_header.hpp
Normal file
94
asio/src/examples/cpp03/icmp/icmp_header.hpp
Normal file
@@ -0,0 +1,94 @@
|
||||
//
|
||||
// icmp_header.hpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef ICMP_HEADER_HPP
|
||||
#define ICMP_HEADER_HPP
|
||||
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <algorithm>
|
||||
|
||||
// ICMP header for both IPv4 and IPv6.
|
||||
//
|
||||
// The wire format of an ICMP header is:
|
||||
//
|
||||
// 0 8 16 31
|
||||
// +---------------+---------------+------------------------------+ ---
|
||||
// | | | | ^
|
||||
// | type | code | checksum | |
|
||||
// | | | | |
|
||||
// +---------------+---------------+------------------------------+ 8 bytes
|
||||
// | | | |
|
||||
// | identifier | sequence number | |
|
||||
// | | | v
|
||||
// +-------------------------------+------------------------------+ ---
|
||||
|
||||
class icmp_header
|
||||
{
|
||||
public:
|
||||
enum { echo_reply = 0, destination_unreachable = 3, source_quench = 4,
|
||||
redirect = 5, echo_request = 8, time_exceeded = 11, parameter_problem = 12,
|
||||
timestamp_request = 13, timestamp_reply = 14, info_request = 15,
|
||||
info_reply = 16, address_request = 17, address_reply = 18 };
|
||||
|
||||
icmp_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }
|
||||
|
||||
unsigned char type() const { return rep_[0]; }
|
||||
unsigned char code() const { return rep_[1]; }
|
||||
unsigned short checksum() const { return decode(2, 3); }
|
||||
unsigned short identifier() const { return decode(4, 5); }
|
||||
unsigned short sequence_number() const { return decode(6, 7); }
|
||||
|
||||
void type(unsigned char n) { rep_[0] = n; }
|
||||
void code(unsigned char n) { rep_[1] = n; }
|
||||
void checksum(unsigned short n) { encode(2, 3, n); }
|
||||
void identifier(unsigned short n) { encode(4, 5, n); }
|
||||
void sequence_number(unsigned short n) { encode(6, 7, n); }
|
||||
|
||||
friend std::istream& operator>>(std::istream& is, icmp_header& header)
|
||||
{ return is.read(reinterpret_cast<char*>(header.rep_), 8); }
|
||||
|
||||
friend std::ostream& operator<<(std::ostream& os, const icmp_header& header)
|
||||
{ return os.write(reinterpret_cast<const char*>(header.rep_), 8); }
|
||||
|
||||
private:
|
||||
unsigned short decode(int a, int b) const
|
||||
{ return (rep_[a] << 8) + rep_[b]; }
|
||||
|
||||
void encode(int a, int b, unsigned short n)
|
||||
{
|
||||
rep_[a] = static_cast<unsigned char>(n >> 8);
|
||||
rep_[b] = static_cast<unsigned char>(n & 0xFF);
|
||||
}
|
||||
|
||||
unsigned char rep_[8];
|
||||
};
|
||||
|
||||
template <typename Iterator>
|
||||
void compute_checksum(icmp_header& header,
|
||||
Iterator body_begin, Iterator body_end)
|
||||
{
|
||||
unsigned int sum = (header.type() << 8) + header.code()
|
||||
+ header.identifier() + header.sequence_number();
|
||||
|
||||
Iterator body_iter = body_begin;
|
||||
while (body_iter != body_end)
|
||||
{
|
||||
sum += (static_cast<unsigned char>(*body_iter++) << 8);
|
||||
if (body_iter != body_end)
|
||||
sum += static_cast<unsigned char>(*body_iter++);
|
||||
}
|
||||
|
||||
sum = (sum >> 16) + (sum & 0xFFFF);
|
||||
sum += (sum >> 16);
|
||||
header.checksum(static_cast<unsigned short>(~sum));
|
||||
}
|
||||
|
||||
#endif // ICMP_HEADER_HPP
|
||||
102
asio/src/examples/cpp03/icmp/ipv4_header.hpp
Normal file
102
asio/src/examples/cpp03/icmp/ipv4_header.hpp
Normal file
@@ -0,0 +1,102 @@
|
||||
//
|
||||
// ipv4_header.hpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef IPV4_HEADER_HPP
|
||||
#define IPV4_HEADER_HPP
|
||||
|
||||
#include <algorithm>
|
||||
#include <asio/ip/address_v4.hpp>
|
||||
|
||||
// Packet header for IPv4.
|
||||
//
|
||||
// The wire format of an IPv4 header is:
|
||||
//
|
||||
// 0 8 16 31
|
||||
// +-------+-------+---------------+------------------------------+ ---
|
||||
// | | | | | ^
|
||||
// |version|header | type of | total length in bytes | |
|
||||
// | (4) | length| service | | |
|
||||
// +-------+-------+---------------+-+-+-+------------------------+ |
|
||||
// | | | | | | |
|
||||
// | identification |0|D|M| fragment offset | |
|
||||
// | | |F|F| | |
|
||||
// +---------------+---------------+-+-+-+------------------------+ |
|
||||
// | | | | |
|
||||
// | time to live | protocol | header checksum | 20 bytes
|
||||
// | | | | |
|
||||
// +---------------+---------------+------------------------------+ |
|
||||
// | | |
|
||||
// | source IPv4 address | |
|
||||
// | | |
|
||||
// +--------------------------------------------------------------+ |
|
||||
// | | |
|
||||
// | destination IPv4 address | |
|
||||
// | | v
|
||||
// +--------------------------------------------------------------+ ---
|
||||
// | | ^
|
||||
// | | |
|
||||
// / options (if any) / 0 - 40
|
||||
// / / bytes
|
||||
// | | |
|
||||
// | | v
|
||||
// +--------------------------------------------------------------+ ---
|
||||
|
||||
class ipv4_header
|
||||
{
|
||||
public:
|
||||
ipv4_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }
|
||||
|
||||
unsigned char version() const { return (rep_[0] >> 4) & 0xF; }
|
||||
unsigned short header_length() const { return (rep_[0] & 0xF) * 4; }
|
||||
unsigned char type_of_service() const { return rep_[1]; }
|
||||
unsigned short total_length() const { return decode(2, 3); }
|
||||
unsigned short identification() const { return decode(4, 5); }
|
||||
bool dont_fragment() const { return (rep_[6] & 0x40) != 0; }
|
||||
bool more_fragments() const { return (rep_[6] & 0x20) != 0; }
|
||||
unsigned short fragment_offset() const { return decode(6, 7) & 0x1FFF; }
|
||||
unsigned int time_to_live() const { return rep_[8]; }
|
||||
unsigned char protocol() const { return rep_[9]; }
|
||||
unsigned short header_checksum() const { return decode(10, 11); }
|
||||
|
||||
asio::ip::address_v4 source_address() const
|
||||
{
|
||||
asio::ip::address_v4::bytes_type bytes
|
||||
= { { rep_[12], rep_[13], rep_[14], rep_[15] } };
|
||||
return asio::ip::address_v4(bytes);
|
||||
}
|
||||
|
||||
asio::ip::address_v4 destination_address() const
|
||||
{
|
||||
asio::ip::address_v4::bytes_type bytes
|
||||
= { { rep_[16], rep_[17], rep_[18], rep_[19] } };
|
||||
return asio::ip::address_v4(bytes);
|
||||
}
|
||||
|
||||
friend std::istream& operator>>(std::istream& is, ipv4_header& header)
|
||||
{
|
||||
is.read(reinterpret_cast<char*>(header.rep_), 20);
|
||||
if (header.version() != 4)
|
||||
is.setstate(std::ios::failbit);
|
||||
std::streamsize options_length = header.header_length() - 20;
|
||||
if (options_length < 0 || options_length > 40)
|
||||
is.setstate(std::ios::failbit);
|
||||
else
|
||||
is.read(reinterpret_cast<char*>(header.rep_) + 20, options_length);
|
||||
return is;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned short decode(int a, int b) const
|
||||
{ return (rep_[a] << 8) + rep_[b]; }
|
||||
|
||||
unsigned char rep_[60];
|
||||
};
|
||||
|
||||
#endif // IPV4_HEADER_HPP
|
||||
163
asio/src/examples/cpp03/icmp/ping.cpp
Normal file
163
asio/src/examples/cpp03/icmp/ping.cpp
Normal file
@@ -0,0 +1,163 @@
|
||||
//
|
||||
// ping.cpp
|
||||
// ~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <istream>
|
||||
#include <iostream>
|
||||
#include <ostream>
|
||||
|
||||
#include "icmp_header.hpp"
|
||||
#include "ipv4_header.hpp"
|
||||
|
||||
using asio::ip::icmp;
|
||||
using asio::steady_timer;
|
||||
namespace chrono = asio::chrono;
|
||||
|
||||
class pinger
|
||||
{
|
||||
public:
|
||||
pinger(asio::io_context& io_context, const char* destination)
|
||||
: resolver_(io_context), socket_(io_context, icmp::v4()),
|
||||
timer_(io_context), sequence_number_(0), num_replies_(0)
|
||||
{
|
||||
destination_ = *resolver_.resolve(icmp::v4(), destination, "").begin();
|
||||
|
||||
start_send();
|
||||
start_receive();
|
||||
}
|
||||
|
||||
private:
|
||||
void start_send()
|
||||
{
|
||||
std::string body("\"Hello!\" from Asio ping.");
|
||||
|
||||
// Create an ICMP header for an echo request.
|
||||
icmp_header echo_request;
|
||||
echo_request.type(icmp_header::echo_request);
|
||||
echo_request.code(0);
|
||||
echo_request.identifier(get_identifier());
|
||||
echo_request.sequence_number(++sequence_number_);
|
||||
compute_checksum(echo_request, body.begin(), body.end());
|
||||
|
||||
// Encode the request packet.
|
||||
asio::streambuf request_buffer;
|
||||
std::ostream os(&request_buffer);
|
||||
os << echo_request << body;
|
||||
|
||||
// Send the request.
|
||||
time_sent_ = steady_timer::clock_type::now();
|
||||
socket_.send_to(request_buffer.data(), destination_);
|
||||
|
||||
// Wait up to five seconds for a reply.
|
||||
num_replies_ = 0;
|
||||
timer_.expires_at(time_sent_ + chrono::seconds(5));
|
||||
timer_.async_wait(boost::bind(&pinger::handle_timeout, this));
|
||||
}
|
||||
|
||||
void handle_timeout()
|
||||
{
|
||||
if (num_replies_ == 0)
|
||||
std::cout << "Request timed out" << std::endl;
|
||||
|
||||
// Requests must be sent no less than one second apart.
|
||||
timer_.expires_at(time_sent_ + chrono::seconds(1));
|
||||
timer_.async_wait(boost::bind(&pinger::start_send, this));
|
||||
}
|
||||
|
||||
void start_receive()
|
||||
{
|
||||
// Discard any data already in the buffer.
|
||||
reply_buffer_.consume(reply_buffer_.size());
|
||||
|
||||
// Wait for a reply. We prepare the buffer to receive up to 64KB.
|
||||
socket_.async_receive(reply_buffer_.prepare(65536),
|
||||
boost::bind(&pinger::handle_receive, this, boost::placeholders::_2));
|
||||
}
|
||||
|
||||
void handle_receive(std::size_t length)
|
||||
{
|
||||
// The actual number of bytes received is committed to the buffer so that we
|
||||
// can extract it using a std::istream object.
|
||||
reply_buffer_.commit(length);
|
||||
|
||||
// Decode the reply packet.
|
||||
std::istream is(&reply_buffer_);
|
||||
ipv4_header ipv4_hdr;
|
||||
icmp_header icmp_hdr;
|
||||
is >> ipv4_hdr >> icmp_hdr;
|
||||
|
||||
// We can receive all ICMP packets received by the host, so we need to
|
||||
// filter out only the echo replies that match the our identifier and
|
||||
// expected sequence number.
|
||||
if (is && icmp_hdr.type() == icmp_header::echo_reply
|
||||
&& icmp_hdr.identifier() == get_identifier()
|
||||
&& icmp_hdr.sequence_number() == sequence_number_)
|
||||
{
|
||||
// If this is the first reply, interrupt the five second timeout.
|
||||
if (num_replies_++ == 0)
|
||||
timer_.cancel();
|
||||
|
||||
// Print out some information about the reply packet.
|
||||
chrono::steady_clock::time_point now = chrono::steady_clock::now();
|
||||
chrono::steady_clock::duration elapsed = now - time_sent_;
|
||||
std::cout << length - ipv4_hdr.header_length()
|
||||
<< " bytes from " << ipv4_hdr.source_address()
|
||||
<< ": icmp_seq=" << icmp_hdr.sequence_number()
|
||||
<< ", ttl=" << ipv4_hdr.time_to_live()
|
||||
<< ", time="
|
||||
<< chrono::duration_cast<chrono::milliseconds>(elapsed).count()
|
||||
<< std::endl;
|
||||
}
|
||||
|
||||
start_receive();
|
||||
}
|
||||
|
||||
static unsigned short get_identifier()
|
||||
{
|
||||
#if defined(ASIO_WINDOWS)
|
||||
return static_cast<unsigned short>(::GetCurrentProcessId());
|
||||
#else
|
||||
return static_cast<unsigned short>(::getpid());
|
||||
#endif
|
||||
}
|
||||
|
||||
icmp::resolver resolver_;
|
||||
icmp::endpoint destination_;
|
||||
icmp::socket socket_;
|
||||
steady_timer timer_;
|
||||
unsigned short sequence_number_;
|
||||
chrono::steady_clock::time_point time_sent_;
|
||||
asio::streambuf reply_buffer_;
|
||||
std::size_t num_replies_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: ping <host>" << std::endl;
|
||||
#if !defined(ASIO_WINDOWS)
|
||||
std::cerr << "(You may need to run this program as root.)" << std::endl;
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
pinger p(io_context, argv[1]);
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
171
asio/src/examples/cpp03/invocation/prioritised_handlers.cpp
Normal file
171
asio/src/examples/cpp03/invocation/prioritised_handlers.cpp
Normal file
@@ -0,0 +1,171 @@
|
||||
//
|
||||
// prioritised_handlers.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include "asio.hpp"
|
||||
#include <boost/function.hpp>
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
class handler_priority_queue : public asio::execution_context
|
||||
{
|
||||
public:
|
||||
void add(int priority, boost::function<void()> function)
|
||||
{
|
||||
handlers_.push(queued_handler(priority, function));
|
||||
}
|
||||
|
||||
void execute_all()
|
||||
{
|
||||
while (!handlers_.empty())
|
||||
{
|
||||
queued_handler handler = handlers_.top();
|
||||
handler.execute();
|
||||
handlers_.pop();
|
||||
}
|
||||
}
|
||||
|
||||
class executor
|
||||
{
|
||||
public:
|
||||
executor(handler_priority_queue& q, int p)
|
||||
: context_(q), priority_(p)
|
||||
{
|
||||
}
|
||||
|
||||
handler_priority_queue& context() const
|
||||
{
|
||||
return context_;
|
||||
}
|
||||
|
||||
template <typename Function, typename Allocator>
|
||||
void dispatch(const Function& f, const Allocator&) const
|
||||
{
|
||||
context_.add(priority_, f);
|
||||
}
|
||||
|
||||
template <typename Function, typename Allocator>
|
||||
void post(const Function& f, const Allocator&) const
|
||||
{
|
||||
context_.add(priority_, f);
|
||||
}
|
||||
|
||||
template <typename Function, typename Allocator>
|
||||
void defer(const Function& f, const Allocator&) const
|
||||
{
|
||||
context_.add(priority_, f);
|
||||
}
|
||||
|
||||
void on_work_started() const {}
|
||||
void on_work_finished() const {}
|
||||
|
||||
bool operator==(const executor& other) const
|
||||
{
|
||||
return &context_ == &other.context_ && priority_ == other.priority_;
|
||||
}
|
||||
|
||||
bool operator!=(const executor& other) const
|
||||
{
|
||||
return !operator==(other);
|
||||
}
|
||||
|
||||
private:
|
||||
handler_priority_queue& context_;
|
||||
int priority_;
|
||||
};
|
||||
|
||||
template <typename Handler>
|
||||
asio::executor_binder<Handler, executor>
|
||||
wrap(int priority, Handler handler)
|
||||
{
|
||||
return asio::bind_executor(executor(*this, priority), handler);
|
||||
}
|
||||
|
||||
private:
|
||||
class queued_handler
|
||||
{
|
||||
public:
|
||||
queued_handler(int p, boost::function<void()> f)
|
||||
: priority_(p), function_(f)
|
||||
{
|
||||
}
|
||||
|
||||
void execute()
|
||||
{
|
||||
function_();
|
||||
}
|
||||
|
||||
friend bool operator<(const queued_handler& a,
|
||||
const queued_handler& b)
|
||||
{
|
||||
return a.priority_ < b.priority_;
|
||||
}
|
||||
|
||||
private:
|
||||
int priority_;
|
||||
boost::function<void()> function_;
|
||||
};
|
||||
|
||||
std::priority_queue<queued_handler> handlers_;
|
||||
};
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
void high_priority_handler(const asio::error_code& /*ec*/)
|
||||
{
|
||||
std::cout << "High priority handler\n";
|
||||
}
|
||||
|
||||
void middle_priority_handler(const asio::error_code& /*ec*/)
|
||||
{
|
||||
std::cout << "Middle priority handler\n";
|
||||
}
|
||||
|
||||
void low_priority_handler()
|
||||
{
|
||||
std::cout << "Low priority handler\n";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
asio::io_context io_context;
|
||||
|
||||
handler_priority_queue pri_queue;
|
||||
|
||||
// Post a completion handler to be run immediately.
|
||||
asio::post(io_context, pri_queue.wrap(0, low_priority_handler));
|
||||
|
||||
// Start an asynchronous accept that will complete immediately.
|
||||
tcp::endpoint endpoint(asio::ip::address_v4::loopback(), 0);
|
||||
tcp::acceptor acceptor(io_context, endpoint);
|
||||
tcp::socket server_socket(io_context);
|
||||
acceptor.async_accept(server_socket,
|
||||
pri_queue.wrap(100, high_priority_handler));
|
||||
tcp::socket client_socket(io_context);
|
||||
client_socket.connect(acceptor.local_endpoint());
|
||||
|
||||
// Set a deadline timer to expire immediately.
|
||||
asio::steady_timer timer(io_context);
|
||||
timer.expires_at(asio::steady_timer::time_point::min());
|
||||
timer.async_wait(pri_queue.wrap(42, middle_priority_handler));
|
||||
|
||||
while (io_context.run_one())
|
||||
{
|
||||
// The custom invocation hook adds the handlers to the priority queue
|
||||
// rather than executing them from within the poll_one() call.
|
||||
while (io_context.poll_one())
|
||||
;
|
||||
|
||||
pri_queue.execute_all();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
44
asio/src/examples/cpp03/iostreams/daytime_client.cpp
Normal file
44
asio/src/examples/cpp03/iostreams/daytime_client.cpp
Normal file
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// daytime_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: daytime_client <host>" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
tcp::iostream s(argv[1], "daytime");
|
||||
if (!s)
|
||||
{
|
||||
std::cout << "Unable to connect: " << s.error().message() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::string line;
|
||||
std::getline(s, line);
|
||||
std::cout << line << std::endl;
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cout << "Exception: " << e.what() << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
51
asio/src/examples/cpp03/iostreams/daytime_server.cpp
Normal file
51
asio/src/examples/cpp03/iostreams/daytime_server.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
//
|
||||
// daytime_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <asio.hpp>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
std::string make_daytime_string()
|
||||
{
|
||||
using namespace std; // For time_t, time and ctime;
|
||||
time_t now = time(0);
|
||||
return ctime(&now);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
asio::io_context io_context;
|
||||
|
||||
tcp::endpoint endpoint(tcp::v4(), 13);
|
||||
tcp::acceptor acceptor(io_context, endpoint);
|
||||
|
||||
for (;;)
|
||||
{
|
||||
tcp::iostream stream;
|
||||
asio::error_code ec;
|
||||
acceptor.accept(stream.socket(), ec);
|
||||
if (!ec)
|
||||
{
|
||||
stream << make_daytime_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << e.what() << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
91
asio/src/examples/cpp03/iostreams/http_client.cpp
Normal file
91
asio/src/examples/cpp03/iostreams/http_client.cpp
Normal file
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// http_client.cpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <asio/ip/tcp.hpp>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cout << "Usage: http_client <server> <path>\n";
|
||||
std::cout << "Example:\n";
|
||||
std::cout << " http_client www.boost.org /LICENSE_1_0.txt\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::ip::tcp::iostream s;
|
||||
|
||||
// The entire sequence of I/O operations must complete within 60 seconds.
|
||||
// If an expiry occurs, the socket is automatically closed and the stream
|
||||
// becomes bad.
|
||||
s.expires_after(asio::chrono::seconds(60));
|
||||
|
||||
// Establish a connection to the server.
|
||||
s.connect(argv[1], "http");
|
||||
if (!s)
|
||||
{
|
||||
std::cout << "Unable to connect: " << s.error().message() << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Send the request. We specify the "Connection: close" header so that the
|
||||
// server will close the socket after transmitting the response. This will
|
||||
// allow us to treat all data up until the EOF as the content.
|
||||
s << "GET " << argv[2] << " HTTP/1.0\r\n";
|
||||
s << "Host: " << argv[1] << "\r\n";
|
||||
s << "Accept: */*\r\n";
|
||||
s << "Connection: close\r\n\r\n";
|
||||
|
||||
// By default, the stream is tied with itself. This means that the stream
|
||||
// automatically flush the buffered output before attempting a read. It is
|
||||
// not necessary not explicitly flush the stream at this point.
|
||||
|
||||
// Check that response is OK.
|
||||
std::string http_version;
|
||||
s >> http_version;
|
||||
unsigned int status_code;
|
||||
s >> status_code;
|
||||
std::string status_message;
|
||||
std::getline(s, status_message);
|
||||
if (!s || http_version.substr(0, 5) != "HTTP/")
|
||||
{
|
||||
std::cout << "Invalid response\n";
|
||||
return 1;
|
||||
}
|
||||
if (status_code != 200)
|
||||
{
|
||||
std::cout << "Response returned with status code " << status_code << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Process the response headers, which are terminated by a blank line.
|
||||
std::string header;
|
||||
while (std::getline(s, header) && header != "\r")
|
||||
std::cout << header << "\n";
|
||||
std::cout << "\n";
|
||||
|
||||
// Write the remaining data to output.
|
||||
std::cout << s.rdbuf();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cout << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
141
asio/src/examples/cpp03/local/connect_pair.cpp
Normal file
141
asio/src/examples/cpp03/local/connect_pair.cpp
Normal file
@@ -0,0 +1,141 @@
|
||||
//
|
||||
// connect_pair.cpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cctype>
|
||||
#include <asio.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
|
||||
#if defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
|
||||
using asio::local::stream_protocol;
|
||||
|
||||
class uppercase_filter
|
||||
{
|
||||
public:
|
||||
uppercase_filter(asio::io_context& io_context)
|
||||
: socket_(io_context)
|
||||
{
|
||||
}
|
||||
|
||||
stream_protocol::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
// Wait for request.
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
boost::bind(&uppercase_filter::handle_read,
|
||||
this, asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
private:
|
||||
void handle_read(const asio::error_code& ec, std::size_t size)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
// Compute result.
|
||||
for (std::size_t i = 0; i < size; ++i)
|
||||
data_[i] = std::toupper(data_[i]);
|
||||
|
||||
// Send result.
|
||||
asio::async_write(socket_, asio::buffer(data_, size),
|
||||
boost::bind(&uppercase_filter::handle_write,
|
||||
this, asio::placeholders::error));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw asio::system_error(ec);
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& ec)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
// Wait for request.
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
boost::bind(&uppercase_filter::handle_read,
|
||||
this, asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
else
|
||||
{
|
||||
throw asio::system_error(ec);
|
||||
}
|
||||
}
|
||||
|
||||
stream_protocol::socket socket_;
|
||||
boost::array<char, 512> data_;
|
||||
};
|
||||
|
||||
void run(asio::io_context* io_context)
|
||||
{
|
||||
try
|
||||
{
|
||||
io_context->run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception in thread: " << e.what() << "\n";
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
try
|
||||
{
|
||||
asio::io_context io_context;
|
||||
|
||||
// Create filter and establish a connection to it.
|
||||
uppercase_filter filter(io_context);
|
||||
stream_protocol::socket socket(io_context);
|
||||
asio::local::connect_pair(socket, filter.socket());
|
||||
filter.start();
|
||||
|
||||
// The io_context runs in a background thread to perform filtering.
|
||||
asio::thread thread(boost::bind(run, &io_context));
|
||||
|
||||
for (;;)
|
||||
{
|
||||
// Collect request from user.
|
||||
std::cout << "Enter a string: ";
|
||||
std::string request;
|
||||
std::getline(std::cin, request);
|
||||
|
||||
// Send request to filter.
|
||||
asio::write(socket, asio::buffer(request));
|
||||
|
||||
// Wait for reply from filter.
|
||||
std::vector<char> reply(request.size());
|
||||
asio::read(socket, asio::buffer(reply));
|
||||
|
||||
// Show reply to user.
|
||||
std::cout << "Result: ";
|
||||
std::cout.write(&reply[0], request.size());
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
# error Local sockets not available on this platform.
|
||||
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
62
asio/src/examples/cpp03/local/iostream_client.cpp
Normal file
62
asio/src/examples/cpp03/local/iostream_client.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
//
|
||||
// stream_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include "asio.hpp"
|
||||
|
||||
#if defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
|
||||
using asio::local::stream_protocol;
|
||||
|
||||
enum { max_length = 1024 };
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: iostream_client <file>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
stream_protocol::endpoint ep(argv[1]);
|
||||
stream_protocol::iostream s(ep);
|
||||
if (!s)
|
||||
{
|
||||
std::cerr << "Unable to connect: " << s.error().message() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
using namespace std; // For strlen.
|
||||
std::cout << "Enter message: ";
|
||||
char request[max_length];
|
||||
std::cin.getline(request, max_length);
|
||||
size_t length = strlen(request);
|
||||
s << request;
|
||||
|
||||
char reply[max_length];
|
||||
s.read(reply, length);
|
||||
std::cout << "Reply is: ";
|
||||
std::cout.write(reply, length);
|
||||
std::cout << "\n";
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
# error Local sockets not available on this platform.
|
||||
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
61
asio/src/examples/cpp03/local/stream_client.cpp
Normal file
61
asio/src/examples/cpp03/local/stream_client.cpp
Normal file
@@ -0,0 +1,61 @@
|
||||
//
|
||||
// stream_client.cpp
|
||||
// ~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include "asio.hpp"
|
||||
|
||||
#if defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
|
||||
using asio::local::stream_protocol;
|
||||
|
||||
enum { max_length = 1024 };
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: stream_client <file>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
stream_protocol::socket s(io_context);
|
||||
s.connect(stream_protocol::endpoint(argv[1]));
|
||||
|
||||
using namespace std; // For strlen.
|
||||
std::cout << "Enter message: ";
|
||||
char request[max_length];
|
||||
std::cin.getline(request, max_length);
|
||||
size_t request_length = strlen(request);
|
||||
asio::write(s, asio::buffer(request, request_length));
|
||||
|
||||
char reply[max_length];
|
||||
size_t reply_length = asio::read(s,
|
||||
asio::buffer(reply, request_length));
|
||||
std::cout << "Reply is: ";
|
||||
std::cout.write(reply, reply_length);
|
||||
std::cout << "\n";
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
# error Local sockets not available on this platform.
|
||||
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
141
asio/src/examples/cpp03/local/stream_server.cpp
Normal file
141
asio/src/examples/cpp03/local/stream_server.cpp
Normal file
@@ -0,0 +1,141 @@
|
||||
//
|
||||
// stream_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include "asio.hpp"
|
||||
|
||||
#if defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
|
||||
using asio::local::stream_protocol;
|
||||
|
||||
class session
|
||||
: public boost::enable_shared_from_this<session>
|
||||
{
|
||||
public:
|
||||
session(asio::io_context& io_context)
|
||||
: socket_(io_context)
|
||||
{
|
||||
}
|
||||
|
||||
stream_protocol::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
boost::bind(&session::handle_read,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void handle_read(const asio::error_code& error,
|
||||
size_t bytes_transferred)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(data_, bytes_transferred),
|
||||
boost::bind(&session::handle_write,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_write(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
socket_.async_read_some(asio::buffer(data_),
|
||||
boost::bind(&session::handle_read,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// The socket used to communicate with the client.
|
||||
stream_protocol::socket socket_;
|
||||
|
||||
// Buffer used to store data received from the client.
|
||||
boost::array<char, 1024> data_;
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<session> session_ptr;
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, const std::string& file)
|
||||
: io_context_(io_context),
|
||||
acceptor_(io_context, stream_protocol::endpoint(file))
|
||||
{
|
||||
session_ptr new_session(new session(io_context_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_accept(session_ptr new_session,
|
||||
const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
new_session->start();
|
||||
}
|
||||
|
||||
new_session.reset(new session(io_context_));
|
||||
acceptor_.async_accept(new_session->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_session,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
private:
|
||||
asio::io_context& io_context_;
|
||||
stream_protocol::acceptor acceptor_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: stream_server <file>\n";
|
||||
std::cerr << "*** WARNING: existing file is removed ***\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
std::remove(argv[1]);
|
||||
server s(io_context, argv[1]);
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
# error Local sockets not available on this platform.
|
||||
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
||||
93
asio/src/examples/cpp03/multicast/receiver.cpp
Normal file
93
asio/src/examples/cpp03/multicast/receiver.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// receiver.cpp
|
||||
// ~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include "asio.hpp"
|
||||
#include "boost/bind/bind.hpp"
|
||||
|
||||
const short multicast_port = 30001;
|
||||
|
||||
class receiver
|
||||
{
|
||||
public:
|
||||
receiver(asio::io_context& io_context,
|
||||
const asio::ip::address& listen_address,
|
||||
const asio::ip::address& multicast_address)
|
||||
: socket_(io_context)
|
||||
{
|
||||
// Create the socket so that multiple may be bound to the same address.
|
||||
asio::ip::udp::endpoint listen_endpoint(
|
||||
listen_address, multicast_port);
|
||||
socket_.open(listen_endpoint.protocol());
|
||||
socket_.set_option(asio::ip::udp::socket::reuse_address(true));
|
||||
socket_.bind(listen_endpoint);
|
||||
|
||||
// Join the multicast group.
|
||||
socket_.set_option(
|
||||
asio::ip::multicast::join_group(multicast_address));
|
||||
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(data_, max_length), sender_endpoint_,
|
||||
boost::bind(&receiver::handle_receive_from, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
|
||||
void handle_receive_from(const asio::error_code& error,
|
||||
size_t bytes_recvd)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
std::cout.write(data_, bytes_recvd);
|
||||
std::cout << std::endl;
|
||||
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(data_, max_length), sender_endpoint_,
|
||||
boost::bind(&receiver::handle_receive_from, this,
|
||||
asio::placeholders::error,
|
||||
asio::placeholders::bytes_transferred));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
asio::ip::udp::socket socket_;
|
||||
asio::ip::udp::endpoint sender_endpoint_;
|
||||
enum { max_length = 1024 };
|
||||
char data_[max_length];
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 3)
|
||||
{
|
||||
std::cerr << "Usage: receiver <listen_address> <multicast_address>\n";
|
||||
std::cerr << " For IPv4, try:\n";
|
||||
std::cerr << " receiver 0.0.0.0 239.255.0.1\n";
|
||||
std::cerr << " For IPv6, try:\n";
|
||||
std::cerr << " receiver 0::0 ff31::8000:1234\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
receiver r(io_context,
|
||||
asio::ip::make_address(argv[1]),
|
||||
asio::ip::make_address(argv[2]));
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
98
asio/src/examples/cpp03/multicast/sender.cpp
Normal file
98
asio/src/examples/cpp03/multicast/sender.cpp
Normal file
@@ -0,0 +1,98 @@
|
||||
//
|
||||
// sender.cpp
|
||||
// ~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include "asio.hpp"
|
||||
#include "boost/bind/bind.hpp"
|
||||
|
||||
const short multicast_port = 30001;
|
||||
const int max_message_count = 10;
|
||||
|
||||
class sender
|
||||
{
|
||||
public:
|
||||
sender(asio::io_context& io_context,
|
||||
const asio::ip::address& multicast_address)
|
||||
: endpoint_(multicast_address, multicast_port),
|
||||
socket_(io_context, endpoint_.protocol()),
|
||||
timer_(io_context),
|
||||
message_count_(0)
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << "Message " << message_count_++;
|
||||
message_ = os.str();
|
||||
|
||||
socket_.async_send_to(
|
||||
asio::buffer(message_), endpoint_,
|
||||
boost::bind(&sender::handle_send_to, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_send_to(const asio::error_code& error)
|
||||
{
|
||||
if (!error && message_count_ < max_message_count)
|
||||
{
|
||||
timer_.expires_after(asio::chrono::seconds(1));
|
||||
timer_.async_wait(
|
||||
boost::bind(&sender::handle_timeout, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_timeout(const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << "Message " << message_count_++;
|
||||
message_ = os.str();
|
||||
|
||||
socket_.async_send_to(
|
||||
asio::buffer(message_), endpoint_,
|
||||
boost::bind(&sender::handle_send_to, this,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
asio::ip::udp::endpoint endpoint_;
|
||||
asio::ip::udp::socket socket_;
|
||||
asio::steady_timer timer_;
|
||||
int message_count_;
|
||||
std::string message_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: sender <multicast_address>\n";
|
||||
std::cerr << " For IPv4, try:\n";
|
||||
std::cerr << " sender 239.255.0.1\n";
|
||||
std::cerr << " For IPv6, try:\n";
|
||||
std::cerr << " sender ff31::8000:1234\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
sender s(io_context, asio::ip::make_address(argv[1]));
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
240
asio/src/examples/cpp03/nonblocking/third_party_lib.cpp
Normal file
240
asio/src/examples/cpp03/nonblocking/third_party_lib.cpp
Normal file
@@ -0,0 +1,240 @@
|
||||
//
|
||||
// third_party_lib.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <asio.hpp>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/bind/bind.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
#include <iostream>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
namespace third_party_lib {
|
||||
|
||||
// Simulation of a third party library that wants to perform read and write
|
||||
// operations directly on a socket. It needs to be polled to determine whether
|
||||
// it requires a read or write operation, and notified when the socket is ready
|
||||
// for reading or writing.
|
||||
class session
|
||||
{
|
||||
public:
|
||||
session(tcp::socket& socket)
|
||||
: socket_(socket),
|
||||
state_(reading)
|
||||
{
|
||||
}
|
||||
|
||||
// Returns true if the third party library wants to be notified when the
|
||||
// socket is ready for reading.
|
||||
bool want_read() const
|
||||
{
|
||||
return state_ == reading;
|
||||
}
|
||||
|
||||
// Notify that third party library that it should perform its read operation.
|
||||
void do_read(asio::error_code& ec)
|
||||
{
|
||||
if (std::size_t len = socket_.read_some(asio::buffer(data_), ec))
|
||||
{
|
||||
write_buffer_ = asio::buffer(data_, len);
|
||||
state_ = writing;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if the third party library wants to be notified when the
|
||||
// socket is ready for writing.
|
||||
bool want_write() const
|
||||
{
|
||||
return state_ == writing;
|
||||
}
|
||||
|
||||
// Notify that third party library that it should perform its write operation.
|
||||
void do_write(asio::error_code& ec)
|
||||
{
|
||||
if (std::size_t len = socket_.write_some(
|
||||
asio::buffer(write_buffer_), ec))
|
||||
{
|
||||
write_buffer_ = write_buffer_ + len;
|
||||
state_ = asio::buffer_size(write_buffer_) > 0 ? writing : reading;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
tcp::socket& socket_;
|
||||
enum { reading, writing } state_;
|
||||
boost::array<char, 128> data_;
|
||||
asio::const_buffer write_buffer_;
|
||||
};
|
||||
|
||||
} // namespace third_party_lib
|
||||
|
||||
// The glue between asio's sockets and the third party library.
|
||||
class connection
|
||||
: public boost::enable_shared_from_this<connection>
|
||||
{
|
||||
public:
|
||||
typedef boost::shared_ptr<connection> pointer;
|
||||
|
||||
static pointer create(const asio::any_io_executor& ex)
|
||||
{
|
||||
return pointer(new connection(ex));
|
||||
}
|
||||
|
||||
tcp::socket& socket()
|
||||
{
|
||||
return socket_;
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
// Put the socket into non-blocking mode.
|
||||
socket_.non_blocking(true);
|
||||
|
||||
start_operations();
|
||||
}
|
||||
|
||||
private:
|
||||
connection(const asio::any_io_executor& ex)
|
||||
: socket_(ex),
|
||||
session_impl_(socket_),
|
||||
read_in_progress_(false),
|
||||
write_in_progress_(false)
|
||||
{
|
||||
}
|
||||
|
||||
void start_operations()
|
||||
{
|
||||
// Start a read operation if the third party library wants one.
|
||||
if (session_impl_.want_read() && !read_in_progress_)
|
||||
{
|
||||
read_in_progress_ = true;
|
||||
socket_.async_wait(tcp::socket::wait_read,
|
||||
boost::bind(&connection::handle_read,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
// Start a write operation if the third party library wants one.
|
||||
if (session_impl_.want_write() && !write_in_progress_)
|
||||
{
|
||||
write_in_progress_ = true;
|
||||
socket_.async_wait(tcp::socket::wait_write,
|
||||
boost::bind(&connection::handle_write,
|
||||
shared_from_this(),
|
||||
asio::placeholders::error));
|
||||
}
|
||||
}
|
||||
|
||||
void handle_read(asio::error_code ec)
|
||||
{
|
||||
read_in_progress_ = false;
|
||||
|
||||
// Notify third party library that it can perform a read.
|
||||
if (!ec)
|
||||
session_impl_.do_read(ec);
|
||||
|
||||
// The third party library successfully performed a read on the socket.
|
||||
// Start new read or write operations based on what it now wants.
|
||||
if (!ec || ec == asio::error::would_block)
|
||||
start_operations();
|
||||
|
||||
// Otherwise, an error occurred. Closing the socket cancels any outstanding
|
||||
// asynchronous read or write operations. The connection object will be
|
||||
// destroyed automatically once those outstanding operations complete.
|
||||
else
|
||||
socket_.close();
|
||||
}
|
||||
|
||||
void handle_write(asio::error_code ec)
|
||||
{
|
||||
write_in_progress_ = false;
|
||||
|
||||
// Notify third party library that it can perform a write.
|
||||
if (!ec)
|
||||
session_impl_.do_write(ec);
|
||||
|
||||
// The third party library successfully performed a write on the socket.
|
||||
// Start new read or write operations based on what it now wants.
|
||||
if (!ec || ec == asio::error::would_block)
|
||||
start_operations();
|
||||
|
||||
// Otherwise, an error occurred. Closing the socket cancels any outstanding
|
||||
// asynchronous read or write operations. The connection object will be
|
||||
// destroyed automatically once those outstanding operations complete.
|
||||
else
|
||||
socket_.close();
|
||||
}
|
||||
|
||||
private:
|
||||
tcp::socket socket_;
|
||||
third_party_lib::session session_impl_;
|
||||
bool read_in_progress_;
|
||||
bool write_in_progress_;
|
||||
};
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, unsigned short port)
|
||||
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
|
||||
{
|
||||
start_accept();
|
||||
}
|
||||
|
||||
private:
|
||||
void start_accept()
|
||||
{
|
||||
connection::pointer new_connection =
|
||||
connection::create(acceptor_.get_executor());
|
||||
|
||||
acceptor_.async_accept(new_connection->socket(),
|
||||
boost::bind(&server::handle_accept, this, new_connection,
|
||||
asio::placeholders::error));
|
||||
}
|
||||
|
||||
void handle_accept(connection::pointer new_connection,
|
||||
const asio::error_code& error)
|
||||
{
|
||||
if (!error)
|
||||
{
|
||||
new_connection->start();
|
||||
}
|
||||
|
||||
start_accept();
|
||||
}
|
||||
|
||||
tcp::acceptor acceptor_;
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
try
|
||||
{
|
||||
if (argc != 2)
|
||||
{
|
||||
std::cerr << "Usage: third_party_lib <port>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
using namespace std; // For atoi.
|
||||
server s(io_context, atoi(argv[1]));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::cerr << "Exception: " << e.what() << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user