井字游戏,第5部分:C ++后端Boost.Beast,HTTP

井字游戏:内容周期

在本文中,我们将考虑使用C ++ Boost.Beast库的后端实现,并使用一个同步服务器的示例。 与上一篇文章相同的功能-我们从后端获得一个从0到8(含)的随机数。 事实证明,举起Beast的容器并不比Flask困难。 最主要的是立即找到一个合适的例子 。 在这里,我为我的项目准备了一个Dockerfile。


图片


该图片摘自本报告的介绍,以引起人们的注意,并为不了解C ++的人们增加了心情和动力。


项目安装

我们在您的计算机上克隆项目:


git clone https://github.com/nomhoi/tic-tac-toe-part5.git 

发射容器:


 cd tic-tac-toe-part5 docker-compose up -d 

我们构建Web应用程序:


 cd front npm install npm run-script build 

http:// localhost打开浏览器。


Docker容器

烧瓶服务已替换为野兽服务。


docker-compose.yml:


 version: '3.6' services: nginx: image: nginx:alpine container_name: nginx volumes: - ./front/public:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf:ro ports: - "80:80" depends_on: - beast networks: - backend beast: container_name: beast build: context: beast/ dockerfile: Dockerfile ports: - "8080:8080" networks: - backend networks: backend: name: backend 

前端

在此,仅更改了配置文件nginx'a default.conf中的设置。


 location /number { proxy_pass http://beast:8080; } 

后端

Dockerfile在这里获取: https : //github.com/vinniefalco/CppCon2018


 FROM ubuntu:bionic AS build # Install tools required for the project RUN apt-get update \ && apt-get install gcc -y \ && apt-get install g++ -y \ && apt-get install cmake -y \ && apt-get install wget -y # Install Boost RUN cd /home \ && wget http://downloads.sourceforge.net/project/boost/boost/1.70.0/boost_1_70_0.tar.gz \ && tar xfz boost_1_70_0.tar.gz \ && rm boost_1_70_0.tar.gz \ && cd boost_1_70_0 \ && ./bootstrap.sh --with-libraries=system \ && ./b2 install # Copy the entire project and build it COPY ./app /cpp/src/project/ WORKDIR /cpp/src/project/ RUN g++ http_server_sync.cpp -o http_server_sync -lpthread FROM ubuntu:bionic COPY --from=build /cpp/src/project /app/ ENTRYPOINT ["/app/http_server_sync", "0.0.0.0", "8080", "/app/wwwroot"] EXPOSE 8080 

如您所见,使用了多阶段组装技术。 在第一阶段,安装了必要的软件包和Boost库,并构建http_server_sync服务器。 在第二阶段,将完成的服务器复制到最终容器,然后在该容器中启动。


此处获取了同步服务器的源代码。 添加了handle_number_request函数来处理/ number处的请求。


 // Return a random number template< class Body, class Allocator, class Send> void handle_number_request( beast::string_view doc_root, http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send) { http::response<http::string_body> res; res.version(11); // HTTP/1.1 res.result(http::status::ok); res.set(http::field::server, "Beast"); res.body() = std::to_string(rand() % 9); res.prepare_payload(); return send(std::move(res)); } 

在响应主体中,我们编写一个从0到8(含)的随机数。


结论

如您所见,Flask帮助我们快速了解了前端和后端之间的交互作用,我们很快获得了整个应用程序的框架。 在Beast上开发后端时,我们已经了解了交互是如何工作的,并且只专注于找到正确的容器并编写后端服务器本身。


作为您的家庭作业,您可以尝试使用多阶段构建来重新制作nginx服务,以便在第一阶段组装前端。 现在,已经配置了nginx服务,从而可以更方便地进行前端开发,而无需进行不必要的组装。


第二项作业:尝试删除Nginx服务,并提高野兽服务中的前端。 我认为应该解决。


在评论中发布您的决定。


第三项任务:沉思可伸缩性的主题-垂直和水平。 如何在一个Web框架中结合使用C ++和Python这两种语言来解决此问题。


GitHub存储库

https://github.com/nomhoi/tic-tac-toe-part5

Source: https://habr.com/ru/post/zh-CN460991/


All Articles