这是一个通过socket编程实现的一个模拟http服务器,在服务器接收到浏览器的连接后,发送一个HTML网页过去,然后在浏览器上显示出来;
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int init_net()
{
int socketfd = socket(AF_INET,SOCK_STREAM,0);
if(socketfd < 0)
{
perror("socket failed");
return -1;
}
int on=1;
int rret = setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
struct sockaddr_in my_addr;
memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9988);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(socketfd,(struct sockaddr *)&my_addr,sizeof(my_addr));
if(ret < 0)
{
perror("bind failed");
close(socketfd);
return -1;
}
ret = listen(socketfd,5);
if(ret == -1)
{
perror("listen failed");
close(socketfd);
return -1;
}
return socketfd;
}
void *func(void *arg)
{
int acceptfd = *(int *)arg;
char head_buf[] = "HTTP/1.1 200 OK\r\nAccept-Ranges: bytes\r\n\
Content-Length: 1024\r\n\
Content-Type: text/html;charset=UTF-8\r\n\
Connection: close\r\n\r\n";
int ret = send(acceptfd,head_buf,strlen(head_buf),0);
if(ret == -1)
{
perror("send failed");
close(acceptfd);
return NULL;
}
char text_buf[] = "<!DOCTYPE html>\n\
<html>\r\n\
<head>\r\n\
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n\
<script>\r\n\
function checkForm()\r\n\
{\r\n\
alert(\"表单已提交!\");\r\n\
}\r\n\
</script>\r\n\
</head>\r\n\
<body>\r\n\
<form action=\"open\" οnsubmit=\"checkForm()\">\r\n\
<label type=\"text\" value=\"开灯\">\r\n\
<input type=\"submit\" value=\"开灯\">\r\n\
</form>\r\n\
<form action=\"close\" οnsubmit=\"checkForm()\">\r\n\
<label type=\"text\" value=\"关灯\">\r\n\
<input type=\"submit\" value=\"关灯\">\r\n\
</form>\r\n\
</body>\r\n\
</html>";
ret = send(acceptfd,text_buf,strlen(text_buf),0);
if(ret < 0)
{
perror("text write failed");
}
pthread_exit(NULL);
}
int main(int argc,char **argv)
{
int socketfd = init_net();
while(1)
{
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
int acceptfd = accept(socketfd,(struct sockaddr*)&addr,&len);
if(acceptfd == -1)
{
perror("acceptfd failed");
close(acceptfd);
return -1;
}
char *ip = inet_ntoa(addr.sin_addr);
printf("\n\n\n有客户端连接:%s\n",ip);
pthread_t pid = -1;
int ret = pthread_create(&pid,NULL,func,&acceptfd);
if(ret != 0)
{
printf("pthread_create failed\n");
continue;
}
pthread_detach(pid);
}
return 0;
}
主要问题:个人仅在局域网内测试过,未在公网上测试(有服务器的可以在公网上测试下是否可行);而且速度有点慢,有想过这个问题但是没有思路,加上有其他事要忙就只能先放到一边