我正在尝试编写一个能够以 C 语言同时处理多个(超过一千个)客户端连接的服务器。每个连接都旨在完成三件事:
- 向服务器发送数据
- 服务器处理数据
- 服务器返回数据给客户端
我正在使用非阻塞套接字和 epoll() 来处理所有连接,但我的问题是在服务器从一个客户端接收到数据之后的那一刻,并且必须调用一个函数,该函数花费几秒钟来处理它之前的数据返回关闭连接之前必须发送回客户端的结果。
我的问题是,当一个客户端的数据“正在烹饪”时,我可以使用什么范例来继续处理更多连接?
每次我需要调用计算函数时,我一直在研究通过创建线程或进程来实现它的可能性,但我不确定考虑到可能的并发连接数是否可行,那就是为什么我来这里是希望有人在这件事上比我更有经验,可以揭示我的无知。
代码片段:
while (1)
{
ssize_t count;
char buf[512];
count = read (events[i].data.fd, buf, sizeof buf); // read the data
if (count == -1)
{
/* If errno == EAGAIN, that means we have read all
data. So go back to the main loop. */
if (errno != EAGAIN)
{
perror ("read");
done = 1;
}
/* Here is where I should call the processing function before
exiting the loop and closing the actual connection */
answer = proc_function(buf);
count = write (events[i].data.fd, answer, sizeof answer); // send the answer to the client
break;
}
...
提前致谢。