C++服务器

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Who_Am_I.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值