一个多平台的系统基本架构(如下图),数据库部分我们以后可以使用HDFS和MapReduce进行分布式存储,之前大致介绍了js和c++交互的几种方式对比,考虑到拓展性和访问效率,还是优先使用HTTP协议。
由于C++并没有封装HTTP的相关接口,所以我们需要自己封装,HTTP属于应用层的协议,其依赖的传输层协议还是TCP(如下图),所以我们可以通过socket的监听来完成http的监听。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#define port 8080
#define message "HTTP server is ready!"
using namespace std;
int main()
{
int local_fd = socket(AF_INET, SOCK_STREAM, 0);
if (local_fd == -1)
{
cout << "socket error!" << endl;
exit(-1);
}
cout << "socket ready!" << endl;
struct sockaddr_in local_addr;
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(port);
local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int res = bind(local_fd, (struct sockaddr *)&local_addr, sizeof(local_addr));
if (res == -1)
{
cout << "bind error!" << endl;
exit(-1);
}
cout << "bind ready!" << endl;
listen(local_fd, 10);
cout << "等待来自客户端的连接...." << endl;
while (true)
{
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int client_fd = accept(local_fd, (struct sockaddr *)&client_addr, &len);
if (client_fd == -1)
{
cout << "accept错误\n"
<< endl;
exit(-1);
}
char *ip = inet_ntoa(client_addr.sin_addr);
cout << "客户机: " << ip << " 连接到本服务器成功!" << endl;
char buff[1024] = {0};
int size = read(client_fd, buff, sizeof(buff));
cout << "Request information:\n"
<< buff << endl;
cout << size << " bytes" << endl;
write(client_fd, message, sizeof(message));
close(client_fd);
}
close(local_fd);
return 0;
}
$ g++ httpd.cpp -o httpd
$ ./httpd
然后通过网页输入自己的https://服务器IP:端口号就可以访问了。
后续只需使用js或java发送get请求,再通过nginx的proxy代理,即可将客户端的请求数据发送到C++的业务服务器进行相关处理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)