HTTP编程:极简版HTTP服务器搭建

HTTP编程:极简版HTTP服务器搭建

极简版http服务器的搭建:

  1. http协议是一种应用层的数据格式约定,在传输层使用tcp协议实现两端传输
  2. http服务器本质就是一个tcp服务器,只是在应用层的业务处理中根据http协议格式解析请求和响应然后做出对应业务请求处理

http_server.c

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<netinet/in.h>//地址结构
#include<arpa/inet.h>//字节序转换接口
#include<sys/socket.h>//套接字接口

#define MAX_LISTEN_NUM 5

int main()
{
	//1.创建套接字
	int sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(sockfd<0){
		perror("socket error");
		return -1;
	}
	//2.绑定地址信息
	struct sockaddr_in addr;
	addr.sin_family=AF_INET;
	addr.sin_port=htons(9000);
	addr.sin_addr.s_addr=inet_addr("0.0.0.0");
	socklen_t len=sizeof(addr);
	int ret = bind(sockfd,(struct sockaddr*)&addr,len);
	if(ret<0){
		perror("bind error");
		return -1;
	}
	//3.开始监听
	ret =listen(sockfd,MAX_LISTEN_NUM);
	if(ret<0){
		perror("listen error");
		return -1;
	}
	//4.获取新连接
	while(1){
		struct sockaddr_in cliaddr;
		int newfd=accept(sockfd,(struct sockaddr*)&cliaddr,&len);
		if(newfd<0){
			perror("accept error");
			continue;
		}	
		//5.使用新连接与客户端通信(收发数据)
		char buf[1024]={0};
		//接收数据
		ret=recv(newfd,buf,1023,0);
		if(ret<0){
			perror("recv error");
			close(newfd);
			continue;
		}else if(ret==0){//返回值为0,表示该客户端已断开连接
			printf("peer shutdown\n");
			close(newfd);
			continue;
		}	
		printf("%s:%d say:\n%s\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port),buf);
		//发送数据
		memset(buf,0x00,1024);
		strcpy(buf,"HTTP/1.1 200 OK\r\n");//首行
		strcat(buf,"Connection: close\r\n");//响应头部字段
		strcat(buf,"Content-Type: text/html\r\n");
		strcat(buf,"Set-Cookie: session_id=123456\r\n");
		char *body="<html><body><h1>Foerver miss you ,my grandparents</h1></body></html>";
		char tmp[1024]={0};
		sprintf(tmp,"Content-Length:%d\r\n",strlen(body));
		strcat(buf,tmp);
		strcat(buf,"\r\n");//空行
		strcat(buf,body);//正文

		
		ret=send(newfd,buf,strlen(buf),0);
		if(ret<0){
			perror("send error");
			close(newfd);
			continue;
		}
		close(newfd);
	}
	//6.关闭套接字
	close(sockfd);
	return 0;
}

通信演示

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值