乐闻世界logo
搜索文章和话题

How to use C to implement HTTP Keep Alive and Websockets function code?

2个答案

1
2

HTTP Keep-Alive

HTTP Keep-Alive is an important feature of the HTTP protocol, enabling multiple HTTP requests/responses to be sent and received over the same TCP connection instead of establishing a new connection for each request. This approach enhances the efficiency and performance of network communication.

To implement HTTP Keep-Alive in C, socket programming is typically used, with the Connection: keep-alive header explicitly specified in the HTTP request. Below is a simple example demonstrating how to implement a Keep-Alive-enabled HTTP client using sockets in C.

c
#include <stdio.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> int main() { int sock; struct sockaddr_in server; char message[1000], server_reply[2000]; // Create socket sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { printf("Could not create socket"); } puts("Socket created"); server.sin_addr.s_addr = inet_addr("192.168.0.1"); // Server IP server.sin_family = AF_INET; server.sin_port = htons(80); // HTTP port // Connect to remote server if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) { perror("Connect failed. Error"); return 1; } puts("Connected\n"); // Send HTTP request strcpy(message, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: keep-alive\r\n\r\n"); if (send(sock, message, strlen(message), 0) < 0) { puts("Send failed"); return 1; } // Receive server reply if (recv(sock, server_reply, 2000, 0) < 0) { puts("recv failed"); return 1; } puts("Server reply :"); puts(server_reply); // Maintain connection for subsequent communication... close(sock); return 0; }

WebSockets

WebSockets provide full-duplex communication capabilities between the client and server. Implementing WebSockets in C involves performing the correct WebSocket handshake followed by sending and receiving data frames over the same connection.

A complete implementation is complex, but the basic steps include:

  1. Create a TCP Socket Connection.
  2. Send the WebSocket Upgrade Request (including the correct Upgrade and Connection request headers).
  3. Parse the response to confirm the server accepts the WebSocket upgrade.
  4. Send and receive WebSocket data frames.

Here is a simplified code example focusing on sending the WebSocket handshake request:

c
#include <stdio.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> int main() { int sock; struct sockaddr_in server; char message[1024], server_reply[2000]; // Create socket sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { printf("Could not create socket\n"); return 1; } printf("Socket created\n"); server.sin_addr.s_addr = inet_addr("192.168.0.1"); server.sin_family = AF_INET; server.sin_port = htons(80); // Connect to remote server if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) { perror("Connect failed. Error"); return 1; } printf("Connected\n"); // Send WebSocket upgrade request strcpy(message, "GET /chat HTTP/1.1\r\n"); strcat(message, "Host: example.com\r\n"); strcat(message, "Upgrade: websocket\r\n"); strcat(message, "Connection: Upgrade\r\n"); strcat(message, "Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n"); strcat(message, "Sec-WebSocket-Version: 13\r\n\r\n"); if (send(sock, message, strlen(message), 0) < 0) { puts("Send failed"); return 1; } // Receive a reply from the server if (recv(sock, server_reply, 2000, 0) < 0) { puts("recv failed"); return 1; } puts("Server reply :"); puts(server_reply); // Close the socket close(sock); return 0; }

These examples provide a foundational framework for implementing HTTP Keep-Alive and WebSockets functionality in C. When developing a complete application, additional considerations such as error handling, more complex data exchange, and security issues must be addressed.

2024年6月29日 12:07 回复

Implementing HTTP Keep-Alive in C

HTTP Keep-Alive is a mechanism that enables multiple HTTP requests and responses to be sent and received over the same TCP connection, rather than establishing a new connection for each request. Implementing this mechanism in C typically involves setting the Connection: keep-alive header in the HTTP response and maintaining the connection open on the server side until the client closes the connection or the server decides to close it.

c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #define PORT 8080 #define BUFFER_SIZE 1024 int main() { int server_fd, new_socket; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[BUFFER_SIZE] = {0}; char *http_response = "HTTP/1.1 200 OK\nContent-Type: text/plain\nConnection: keep-alive\n\nHello, world!"; // Create socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Bind socket to port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } while(1) { if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } read(new_socket, buffer, BUFFER_SIZE); printf("%s\n", buffer); send(new_socket, http_response, strlen(http_response), 0); // Note: To maintain the connection, we do not close new_socket here } return 0; }

Implementing WebSockets in C

WebSockets provide full-duplex communication over a single long-lived connection, commonly used for real-time data exchange between web pages and servers. Implementing WebSockets in C involves more complexity, such as handling the handshake protocol and frame control.

c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 8080 void error(const char *msg) { perror(msg); exit(1); } int main(int argc, char *argv[]) { int sockfd, newsockfd; socklen_t clilen; char buffer[1024]; struct sockaddr_in serv_addr, cli_addr; int n; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(PORT); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); bzero(buffer,1024); n = read(newsockfd, buffer, 1023); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); n = write(newsockfd, "I got your message", 18); if (n < 0) error("ERROR writing to socket"); close(newsockfd); close(sockfd); return 0; }

This example code demonstrates how to create a framework for a WebSocket server, but additional code is required to handle the WebSocket handshake and data frames, which typically involves more details such as parsing HTTP request headers, generating and parsing specific control frames. For a complete WebSocket server implementation, you may need to use specialized libraries such as libwebsocket.

2024年6月29日 12:07 回复

你的答案