实验四 Web服务器2
基于华为鲲鹏云服务器CentOS中(或Ubuntu),使用Linux Socket实现: 1. Web服务器的客户端服务器,提交程序运行截图 2. 实现GET即可,请求,响应要符合HTTP协议规范 3. 服务器部署到华为云服务器,浏览器用本机的 4. 把服务器部署到试验箱。(加分项)
web_server.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 #include <unistd.h> 7 8 void handle_client(int client_socket) { 9 char response[] = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n<html><body><h1>Hello, this is a simple web server!</h1></body></html>\n"; 10 send(client_socket, response, strlen(response), 0); 11 close(client_socket); 12 } 13 14 int main() { 15 int server_fd, new_socket; 16 struct sockaddr_in address; 17 int opt = 1; 18 int addrlen = sizeof(address); 19 20 if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { 21 perror("socket failed"); 22 exit(EXIT_FAILURE); 23 } 24 25 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { 26 perror("setsockopt"); 27 exit(EXIT_FAILURE); 28 } 29 30 address.sin_family = AF_INET; 31 address.sin_addr.s_addr = INADDR_ANY; 32 address.sin_port = htons(8080); 33 34 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { 35 perror("bind failed"); 36 exit(EXIT_FAILURE); 37 } 38 39 if (listen(server_fd, 3) < 0) { 40 perror("listen"); 41 exit(EXIT_FAILURE); 42 } 43 44 while (1) { 45 if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { 46 perror("accept"); 47 exit(EXIT_FAILURE); 48 } 49 handle_client(new_socket); 50 } 51 return 0; 52 }
web_client.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 #include <unistd.h> 7 #include <arpa/inet.h> 8 9 int main() { 10 struct sockaddr_in serv_addr; 11 int sock = 0, valread; 12 char buffer[1024] = {0}; 13 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 14 printf("\n Socket creation error \n"); 15 return -1; 16 } 17 serv_addr.sin_family = AF_INET; 18 serv_addr.sin_port = htons(8080); 19 if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) { 20 printf("\nInvalid address/ Address not supported \n"); 21 return -1; 22 } 23 if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { 24 printf("\nConnection Failed \n"); 25 return -1; 26 } 27 char message[] = "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; 28 send(sock, message, strlen(message), 0); 29 30 while ((valread = read(sock, buffer, 1023)) > 0) { 31 buffer[valread] = '\0'; 32 printf("%s", buffer); 33 } 34 35 return 0; 36 }
运行截图:
标签:Web,addr,int,实验,address,服务器,include,socket From: https://www.cnblogs.com/20211115fyq/p/17884234.html