用C语言编写的简易web server,HTTP/1.1,运行环境:Ubuntu 18.04
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_LISTEN 10
#define K 1024
#define IP "127.0.0.1"
#define PORT 34478
static struct sockaddr_in server,client;
static int s,sc[MAX_LISTEN];
static int max_flag=0;
static char wbuf[10*K];
static char rbuf[10*K];
static pthread_t th[MAX_LISTEN];
static void Init(void);
static unsigned char respond_pack(char *buf);
static void *thread_fun(void *arg);
int main(int argc,char *argv[]){
Init();
int i=0,len;
len=sizeof(struct sockaddr);
while(1){
while(max_flag==MAX_LISTEN);
if((sc[i]=accept(s,(struct sockaddr*)&client,&len))==-1){
printf("accept %d error,errno is %d\n",i,errno);
continue;
}
if(pthread_create(&th[i],NULL,thread_fun,(void *)i)!=0){
printf("pthread create %d error,errno is %d\n",i,errno);
}
i++;
if(i>=MAX_LISTEN){
i=0;
}
}
return 0;
}
static void Init(void){
int err;
if((s=socket(AF_INET,SOCK_STREAM,0))==-1){
printf("socket failed,errno is %d\n",errno);
exit(-1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=inet_addr(IP);
if(bind(s,(struct sockaddr *)&server,sizeof(server))==-1){
printf("bind error,errno is %d\n",errno);
perror("bind");
exit(-1);
}
listen(s,MAX_LISTEN);
}
static unsigned char respond_pack(char *buf){
int fd,num=0;
char datefile[2*K];
bzero(buf,sizeof(buf));
if((fd=open("www/index.html",O_RDWR))==-1){
printf("open failed,errno is %d\n",errno);
exit(-1);
}
do{
num=read(fd,datefile,124);
if(num<0){
printf("read failed,errno is %d\n",errno);
sleep(1);
continue;
}
}while(num==124);
close(fd);
sprintf(buf,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html;charset=iso-8859-1\r\n"
"\r\n"
"%s\r\n",
datefile);
return 0;
}
static void *thread_fun(void *arg){
int num=0;
int i=(int)arg;
max_flag++;
while(1){
num=recv(sc[i],rbuf,sizeof(rbuf),0);
if(num<0){
printf("read error,errno is %d\n",errno);
break;
}else{
printf("%s\n",rbuf);
respond_pack(wbuf);
num=send(sc[i],wbuf,strlen(wbuf),0);
if(num<0){
printf("send error,errno is %d\n",errno);
sleep(1);
break;
}
break;
}
}
close(sc[i]);
max_flag--;
pthread_exit((void *)11);
}
Makefile:
all:
gcc web_server.c -o web_server -lpthread
clean:
rm web_server
运行:
1、运行web_server
am@ubuntu web_server$ ./web_server
2、打开浏览器,输入:127.0.0.1:34478
查看结果:
1、查看终端、终端打印如下:
GET / HTTP/1.1
Host: 127.0.0.1:34478
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
2、浏览器访问结果如下图: