c - C 中套接字的频繁读/写操作

标签 c sockets server

我想用 C 语言为服务器(套接字编程)编写一个脚本,该脚本将处于监听模式,并读取来自客户端的 HTTP 请求并对该请求执行一些操作。

例如: 假设我收到的请求如下:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><line2:connectionClearedEvent><cause>normalClearing</cause></line2:connectionClearedEvent></SOAP-ENV:Body></SOAP-ENV:Envelope>

我想检查请求是否包含“connectionClearedEvent”字符串,然后将计数器加一。

问题:

第一个想法 假设服务器上有负载,如果实现将所有来自套接字的请求写入文件,那么由于频繁的写入操作,它会跳过一些请求。

第二个想法 假设服务器上有负载,如果实现只是读取传入请求并搜索该关键字,那么也会由于频繁的读取操作而跳过某些请求。

当服务器有大量请求时,任何人都可以建议一种方法来执行上述操作。

编辑:相同的代码 connection_handler() 将处理每个客户端的连接,但我现在面临的问题是处理文件。

#include<stdio.h>
#include<string.h>    //strlen
#include<stdlib.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h>    //write
#include<pthread.h> //for threading , link with lpthread

//the thread function
void *connection_handler(void *);

int main(int argc , char *argv[])
{
	printf("Program name %s\n", argv[0]);
	if( argc == 2 )
	{
		printf("The argument supplied is %s\n", argv[1]);
	}
	else if( argc > 2 )
	{
		printf("Too many arguments supplied.\n");
	}
	else 
	{
		printf("Server Port not provided..exiting \n");
		// scanf("%s",&argv[1]);
		return 1;  
	}
	
    int socket_desc , client_sock , c , *new_sock;
    struct sockaddr_in server , client;
	
    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
	}
    puts("Socket created");
	
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(atoi(argv[1]));
	
    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
	}
    puts("bind done");
	
    //Listen
    listen(socket_desc , 3);
	
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
	
	
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        puts("Connection accepted");
		
        pthread_t sniffer_thread;
        new_sock = malloc(1);
        *new_sock = client_sock;
		
        if( pthread_create( &sniffer_thread , NULL ,  connection_handler , (void*) new_sock) < 0)
        {
            perror("could not create thread");
            return 1;
		}
		
        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( sniffer_thread , NULL);
        puts("Handler assigned");
	}
	
    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
	}
	
    return 0;
}

/*
	* This will handle connection for each client
* */
void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];
	
	static char* ok_response =
	"HTTP/1.1 200 OK\r\n"
	"Content-Length: 101\r\n"
	"Content-type: text/xml; charset=utf-8\r\n"
	"\r\n"
	"<html>\n"
	" <body>\n"
	"  <h1>Bad Request</h1>\n"
	"  <p>This server understand your request.</p>\n"
	" </body>\n"
	"</html>\n";
	
	static char* body =
	"<html>\n"
	" <body>\n"
	"  <h1>Bad Request</h1>\n"
	"  <p>This server understand your request.</p>\n"
	" </body>\n"
	"</html>\n";
	
	printf("content length : %d\n",strlen(body));
    
   //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
		puts(client_message);
        write(sock , ok_response , strlen(ok_response));
		memset (client_message,'\0',2000);
	}
	
    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
	}
    else if(read_size == -1)
    {
        perror("recv failed");
	}
	
    //Free the socket pointer
    free(socket_desc);
	
    return 0;
}

最佳答案

这里主要要做三件事(可以组合):

  1. 增加listening队列 ( listen(socket, <number of pending requests>) ) - 这将有助于处理突发请求,但如果您处理请求的速度不够快,这最终也会失败

  2. 将您的工作量分配给多个 workers利用现代多线程和多处理环境。这可以通过线程或进程来完成,其中对于每个请求,在 accept 之后在传入连接后,新的连接套接字将交给工作线程/进程来处理。 这样,您在处理请求时就不会阻塞监听套接字。如果您的服务器过载,这也只能扩展到最终耗尽工作人员的程度。

  3. Clustering - 最终,单个服务器/机器可能无法处理传入负载。您需要创建一个负载平衡机制,并将请求转移到不同的机器上进行处理。

关于c - C 中套接字的频繁读/写操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45609486/

相关文章:

c - 写入syslog会导致堆分配的大小稳定增加

c - 在 C 中使用 strtoul

python - Python 中使用 SimpleXMLRPCServer 进行客户端/服务器角色逆转

apache - VirtualHost:停用 SSL 的全部捕获 (443)

c - 在文件名中添加数字

c - 为什么直接将值传递给 sizeof 运算符时,数据类型的大小会不同?

c - 如何处理 Hook 的 WSARecv

linux - 设计 UDP 服务器的最佳方法是什么?

java - 如何获取运行 Web 服务的端口号?

java - 嵌入式 Cassandra 服务器获取 "java.lang.reflect.InvocationTargetException"