在C語言中,我們經常會需要攔截HTTP請求并返回JSON數據。這可以通過基于Socket的HTTP服務器來實現。下面是一個簡單的例子:
#include#include #include #include #include #include #define MAX_BUFFER_SIZE 1024 int main() { // 創建套接字 int server_socket = socket(AF_INET, SOCK_STREAM, 0); if (server_socket == -1) { perror("Failed to create socket"); return 1; } // 綁定端口 struct sockaddr_in server_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(8080); server_address.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) == -1) { perror("Failed to bind port 8080"); return 1; } // 監聽 if (listen(server_socket, 5) == -1) { perror("Failed to listen"); return 1; } // 處理HTTP請求 while (1) { int client_socket = accept(server_socket, NULL, NULL); if (client_socket< 0) { perror("Failed to accept"); return 1; } // 讀取請求 char buffer[MAX_BUFFER_SIZE]; int size = read(client_socket, buffer, MAX_BUFFER_SIZE); if (size == -1) { perror("Failed to read request"); return 1; } // 響應JSON數據 const char* response = "{ \"message\": \"Hello, World!\" }"; char header[MAX_BUFFER_SIZE]; snprintf(header, MAX_BUFFER_SIZE, "HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: application/json\r\n\r\n", strlen(response)); if (write(client_socket, header, strlen(header)) == -1) { perror("Failed to write response header"); return 1; } if (write(client_socket, response, strlen(response)) == -1) { perror("Failed to write response body"); return 1; } // 關閉客戶端套接字 close(client_socket); } // 關閉服務器套接字 close(server_socket); return 0; }
上述代碼創建了一個基于Socket的HTTP服務器,并通過讀取HTTP請求并返回JSON數據來響應客戶端請求。我們可以使用curl來測試該服務器:
$ curl http://localhost:8080 { "message": "Hello, World!" }
該服務器返回了一個JSON對象,其中包含了一條消息:"Hello, World!"。這個例子可以作為一個基礎模板,用于構建更復雜的HTTP服務器。
上一篇vue中的reload
下一篇ie vue內存增長