#include<stdio.h>
#include<string>
#include<iostream>
#include <sys/types.h>
#include<map>
#include <ctime>
#include<sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <map>
#include <string.h>
using namespace std;
//最大传输大小
#define MAXSIZE 1024
#define SERVER_PORT 8980
#define BACKLOG 10
//按行读取接收报文
string ReadLine(char recieve[], int &loc)
{
int next_char;
string data = "";
while (true)
{
next_char = recieve[loc++];
if (next_char == '\n')
{
break;
}
else if (next_char == '\r')
{
continue;
}
else if (next_char == '\0')
{
break;
}
data += next_char;
}
return data;
}
//处理HTTP请求类
class HttpRequestHandle {
public:
//初始化
HttpRequestHandle(unsigned char recieved[]) {
memcpy(recieve, recieved, MAXSIZE);
loc = 0;
Http_method = "";
Http_url = "";
}
//获得请求头
void GetHeadInfo() {
string line;
string head = ReadLine(recieve, loc);//请求行
//获得方法
int loc_head = 0;
while (head[loc_head] != ' ') {
Http_method += head[loc_head];
loc_head++;
}
loc_head++;
while (head[loc_head] != ' ') {
Http_url += head[loc_head];
loc_head++;
}
while ((line = ReadLine(recieve, loc)) != "") {
//分解报文头
int seq_index = line.find_first_of(":");
if (seq_index != -1) {
string type = line.substr(0,seq_index);
string value = line.substr(seq_index+1,line.size());
HttpHeaders.insert(make_pair(type,value));
}
cout << line << endl;
}
}
void GetHttpBody() {
while (recieve[loc] != '\0') {
body += recieve[loc];
loc++;
}
}
string GetMethod() {
return Http_method;
}
string GetURL() {
return Http_url;
}
string GetBody() {
return body;
}
private:
char recieve[MAXSIZE];//接收字符
string Http_method;//请求方式
string Http_url;//URL地址
string body;
map<string, string> HttpHeaders;
int loc;//读取位置
};
//处理方法类
class MyFunction {
public:
MyFunction(string Http_method, string Http_url, string body) {
this->body = body;
this->Http_method = Http_method;
this->Http_url = Http_url;
}
string Deal() {
string deal_str = "";
if (Http_method == "GET") {
int id = choose();
switch (id) {
case 1:
deal_str = test();
break;
default:
break;
}
}
else if (Http_method == "POST") {
}
return deal_str;
}
//根据URL选择方法
int choose() {
if (Http_url == "") {
}
else {
return 1;
}
}
//方法1:测试用
string test() {
return "hello";
}
private:
string Http_method;//请求方式
string Http_url;//URL地址
string body;
};
class HttpResponseHandle {
public:
HttpResponseHandle(string send) {
this->send = send;
Http_State = "200";//成功状态
Http_phrase = "OK";
Http_protocol_versionstring = "HTTP/1.1";
//HttpHeaders.insert({ "Date",t.tm_year+1900+"" });
HttpHeaders.insert(make_pair("Content-Type","application/json; charset=UTF-8" ));
HttpHeaders.insert(make_pair("Content-Length","0"));
}
void SetSend() {
string headerstr = "";
headerstr = Http_protocol_versionstring + " " + Http_State + " " + Http_phrase + "\r\n";
string Header_line = "";
map<string, string>::reverse_iterator iter;
HttpHeaders["Content-Length"] = ""+send.size();
for (iter = HttpHeaders.rbegin(); iter != HttpHeaders.rend(); iter++) {
Header_line += iter->first + ":" + iter->second + "\r\n";
}
headerstr += Header_line ;
send = headerstr + "\r\n" + send;
}
string GetSend() {
return send;
}
private:
string Http_State;
string Http_phrase;
string Http_protocol_versionstring;
map<string, string> HttpHeaders;
string send;
};
int main()
{
socklen_t iSocketServer;
int iSocketClient;
struct sockaddr_in tSocketServerAddr;
struct sockaddr_in tSocketClientAddr;
int iRet;
socklen_t iAddrLen;
int iRecvLen;
unsigned char ucRecvBuf[1000];
int iClientNum = -1;
signal(SIGCHLD,SIG_IGN);
iSocketServer = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == iSocketServer)
{
printf("socket error!\n");
return -1;
}
tSocketServerAddr.sin_family = AF_INET;
tSocketServerAddr.sin_port = htons(SERVER_PORT); /* host to net, short */
tSocketServerAddr.sin_addr.s_addr = INADDR_ANY;
memset(tSocketServerAddr.sin_zero, 0, 8);
iRet = bind(iSocketServer, (const struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
// 设置socket为non-block
if (-1 == iRet)
{
printf("bind error!\n");
return -1;
}
iRet = listen(iSocketServer, BACKLOG);
if (-1 == iRet)
{
printf("listen error!\n");
return -1;
}
while (1)
{
iAddrLen = sizeof(struct sockaddr);
// 增加 select 或者 epoll 观察 socket的状态
iSocketClient = accept(iSocketServer, (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
if (-1 != iSocketClient)
{
iClientNum++;
printf("Get connect from client %d : %s\n", iClientNum, inet_ntoa(tSocketClientAddr.sin_addr));
if (!fork()) // 不要使用fork
{
/* 子进程的源码 */
while (1)
{
/* 接收客户端发来的数据并显示出来 */
// 先select 或epoll 再recv
iRecvLen = recv(iSocketClient, ucRecvBuf, MAXSIZE, 0);
if (iRecvLen <= 0)
{
close(iSocketClient);
}
else
{
ucRecvBuf[iRecvLen] = '\0';
cout<<"Request"<<endl;
HttpRequestHandle httpreq(ucRecvBuf);
httpreq.GetHeadInfo();
httpreq.GetHttpBody();
MyFunction function(httpreq.GetMethod(), httpreq.GetURL(), httpreq.GetBody());
string response_str = function.Deal();
HttpResponseHandle response(response_str);
response.SetSend();
string send_str = response.GetSend();
if(!fork()){ /*紫禁城*/
cout<<"Response"<<endl;
if(send(iSocketClient, send_str.c_str(), strlen(send_str.c_str()), 0) == -1)
{
perror("send error");
}
close(iSocketClient);
}
}
}
}
}
}
close(iSocketServer);
return 0;
}
C++服务器
最新推荐文章于 2024-02-07 10:59:37 发布