标签: 实现一个简单的http服务器 Linux实现一个简单的http服务器 实现一个简单的http服务器的代码及其应用

代码实现

Makefile :

  1. .PHONY:all clean
  2. all:http_server
  3. http_server:http_server.c
  4. gcc $^ -o $@ -lpthread
  5. clean:
  6. rm -rf http_server

http_server.c :

  1. #include <stdio.h>
  2. #include <netinet/in.h>
  3. #include <arpa/inet.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <sys/socket.h>
  7. #include <pthread.h>
  8. #include <stdlib.h>
  9. int startup()
  10. {
  11. int sock = socket(AF_INET,SOCK_STREAM,0);
  12. if(sock < 0)
  13. {
  14. exit(1);
  15. }
  16. int opt = 1;
  17. setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
  18. struct sockaddr_in local;
  19. local.sin_family = AF_INET;
  20. local.sin_addr.s_addr = htonl(INADDR_ANY);
  21. local.sin_port = htons(8080);
  22. int ret = bind(sock,(struct sockaddr *)&local,sizeof(local));
  23. if( ret < 0 )
  24. {
  25. exit(2);
  26. }
  27. if( listen(sock,5) < 0 )
  28. {
  29. exit(3);
  30. }
  31. return sock;
  32. }
  33. void* handler_request(void * arg)
  34. {
  35. int sock = (int)arg;
  36. char buf[4896];
  37. ssize_t s = read(sock,buf,sizeof(buf)-1);
  38. if( s > 0 )
  39. {
  40. buf[s] = 0;
  41. printf(" %s ",buf);
  42. const char *echo_str = "HTTP/1.0 200 ok\n\n<html><h1>Welcome to my http server!</h1><html>\n";
  43. write(sock,echo_str,strlen(echo_str));
  44. }
  45. close(sock);
  46. }
  47. int main()
  48. {
  49. int listen_sock = startup();
  50. while(1)
  51. {
  52. struct sockaddr_in client;
  53. socklen_t len = sizeof(client);
  54. int sock = accept(listen_sock,(struct sockaddr*)&client,&len);
  55. if(sock < 0)
  56. {
  57. continue;
  58. }
  59. pthread_t tid;
  60. pthread_create(&tid,NULL,handler_request,(void *)sock);
  61. pthread_detach(tid);
  62. }
  63. return 0;
  64. }

测试:

必须在一个局域网(网段)中,才能访问到,也就是客户端和服务器端连接一个路由器。

服务器端:

Linux实现一个简单的HTTP服务器 - 图1

客户端:

手机:
Linux实现一个简单的HTTP服务器 - 图2

电脑:

Linux实现一个简单的HTTP服务器 - 图3

参考资料