嵌入式linux最简单webserver

2019-07-12 18:05发布

现在智能家居越來越多了,好多设备都可以用手机控制,而手机通常又通过wifi网络与设备交互! 特点是实时性要求不高,而且都是随时进行的,所以很想访问web页面,所以http方式很适合 以下是linux简单web源码,可以放入到嵌入式设备,通过web或者app可以控制和查询硬件信息,比如 书梅派 #include #include #include // socket #include // 基本数据类型 #include // read write #include #include #include // open close #include #include #define PORT 8888 #define SERV "0.0.0.0" #define QUEUE 20 #define BUFF_SIZE 1024 typedef struct doc_type{ char *key; char *value; }HTTP_CONTENT_TYPE; HTTP_CONTENT_TYPE http_content_type[] = { { "html","text/html" }, { "gif" ,"image/gif" }, { "jpeg","image/jpeg" } }; int sockfd; char *http_res_tmpl = "HTTP/1.1 200 OK " "Server: Cleey's Server V1.0 " "Accept-Ranges: bytes " "Content-Length: %d " "Connection: close " "Content-Type: %s "; void handle_signal(int sign); // 退出信号处理 void http_send(int sock,char *content); // http 发送相应报文 int main(){ signal(SIGINT,handle_signal); int count = 0; // 计数 // 定义 socket sockfd = socket(AF_INET,SOCK_STREAM,0); // 定义 sockaddr_in struct sockaddr_in skaddr; skaddr.sin_family = AF_INET; // ipv4 skaddr.sin_port = htons(PORT); skaddr.sin_addr.s_addr = inet_addr(SERV); // bind,绑定 socket 和 sockaddr_in if( bind(sockfd,(struct sockaddr *)&skaddr,sizeof(skaddr)) == -1 ){ perror("bind error"); exit(1); } // listen,开始添加端口 if( listen(sockfd,QUEUE) == -1 ){ perror("listen error"); exit(1); } // 客户端信息 char buff[BUFF_SIZE]; struct sockaddr_in claddr; socklen_t length = sizeof(claddr); while(1){ int sock_client = accept(sockfd,(struct sockaddr *)&claddr, &length); printf("%d ",++count); if( sock_client <0 ){ perror("accept error"); exit(1); } memset(buff,0,sizeof(buff)); int len = recv(sock_client,buff,sizeof(buff),0); fputs(buff,stdout); //send(sock_client,buff,len,0); http_send(sock_client,"Hello World!"); close(sock_client); if(count > 3) break; } fputs("Bye Cleey",stdout); close(sockfd); return 0; } void http_send(int sock_client,char *content){ char HTTP_HEADER[BUFF_SIZE],HTTP_INFO[BUFF_SIZE]; int len = strlen(content); sprintf(HTTP_HEADER,http_res_tmpl,len,"text/html"); len = sprintf(HTTP_INFO,"%s%s",HTTP_HEADER,content); send(sock_client,HTTP_INFO,len,0); } void handle_signal(int sign){ fputs(" SIGNAL INTERRUPT Bye Cleey! SAFE EXIT ",stdout); close(sockfd); exit(0); }