【发布时间】:2013-07-10 14:32:32
【问题描述】:
我正在尝试用 C 语言编写一个能够同时处理多个(超过一千个)客户端连接的服务器。每个连接都意味着完成三件事:
- 向服务器发送数据
- 服务器处理数据
- 服务器向客户端返回数据
我正在使用非阻塞套接字和 epoll() 来处理所有连接,但我的问题是在服务器从一个客户端接收数据并且必须调用一个花费几秒钟处理数据返回之前必须在关闭连接之前发送回客户端的结果。
我的问题是,我可以使用什么范例以便能够在一个客户端的数据“正在烹饪”时继续处理更多的连接?
我一直在研究通过每次创建线程或进程来实现它的可能性我需要调用计算函数,但我不确定这是否会考虑到可能的并发连接数量,这就是为什么我来到这里希望有人在这件事上比我更有经验的人可以阐明我的无知。
代码 sn-p:
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;
}
...
提前致谢。
【问题讨论】:
标签: c linux concurrency tcp epoll